diff --git a/.gitattributes b/.gitattributes index ee7b116038fe0c4c64db8cd907c174133fd07b6a..744620a66947ebded95ad9d7900ae4ca4a150461 100644 --- a/.gitattributes +++ b/.gitattributes @@ -77,3 +77,7 @@ source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/examples/invoice/src source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/examples/invoice/src/main/webapp/assets/fonts/IBMPlexSans-BoldItalic.otf filter=lfs diff=lfs merge=lfs -text source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/examples/invoice/src/main/webapp/assets/fonts/IBMPlexSans-Italic.otf filter=lfs diff=lfs merge=lfs -text source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/examples/invoice/src/main/webapp/assets/fonts/IBMPlexSans-Regular.otf filter=lfs diff=lfs merge=lfs -text +source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-commons-ui/vendor/fonts/IBMPlexSans-Bold.otf filter=lfs diff=lfs merge=lfs -text +source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-commons-ui/vendor/fonts/IBMPlexSans-BoldItalic.otf filter=lfs diff=lfs merge=lfs -text +source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-commons-ui/vendor/fonts/IBMPlexSans-Italic.otf filter=lfs diff=lfs merge=lfs -text +source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-commons-ui/vendor/fonts/IBMPlexSans-Regular.otf filter=lfs diff=lfs merge=lfs -text diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly-jakarta/assembly.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly-jakarta/assembly.xml new file mode 100644 index 0000000000000000000000000000000000000000..2f9acdf04c2f05ee40e0342dd6e5e3199306e2bb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly-jakarta/assembly.xml @@ -0,0 +1,31 @@ + + + frontend-sources + + zip + + camunda-webapp-jakarta-frontend-sources + + + + / + ../frontend + + + + **/node_modules/** + **/.idea/** + **/.settings/** + **/dist/** + camunda-commons-ui/cache/** + ui/cockpit/build/** + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly-jakarta/pom.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly-jakarta/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..535dda27bea281e5c7bcc16d5cb3f48c1051699d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly-jakarta/pom.xml @@ -0,0 +1,692 @@ + + + + 4.0.0 + + + org.camunda.bpm.webapp + camunda-webapp-root + 7.24.0-SNAPSHOT + ../ + + + camunda-webapp-jakarta + war + + + Note: 7.24.0 is the last community edition release published on Maven Central. This library will not receive any new versions or releases. However, if you are interested in extended maintenance you could look into our enterprise edition. Get in touch with us: https://camunda.com/contact/ + + Camunda Platform - Webapp - Assembly Jakarta + + + ${project.build.directory}/generated-resources/jakarta-webapp + ${project.build.directory}/generated-resources/jakarta-runtime + + 6.2.8.Final + 11.0.14 + 3.1.1 + + ${jakarta.runtime}/default/webapp + ${jakarta.runtime}/default/resources + ${jakarta.runtime}/default/config.properties + + + false + + + + + + org.camunda.bpm + camunda-engine-rest-core-jakarta + ${project.version} + + + org.camunda.bpm + camunda-engine-rest-jakarta + ${project.version} + + + jakarta.platform + jakarta.jakartaee-bom + ${version.jakarta-ee-spec} + pom + import + + + com.fasterxml.jackson + jackson-bom + ${version.jackson} + import + pom + + + + + + + + com.fasterxml.jackson.jakarta.rs + jackson-jakarta-rs-json-provider + + + jakarta.activation + jakarta.activation-api + + + jakarta.xml.bind + jakarta.xml.bind-api + + + + + + com.fasterxml.jackson.core + jackson-databind + + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + + jakarta.servlet + jakarta.servlet-api + provided + + + jakarta.activation + jakarta.activation-api + provided + + + jakarta.ws.rs + jakarta.ws.rs-api + provided + + + jakarta.xml.bind + jakarta.xml.bind-api + provided + + + + org.camunda.bpm + camunda-engine-rest-core-jakarta + + + + org.camunda.bpm + camunda-engine-rest-core-jakarta + ${project.version} + test + tests + + + + + camunda-webapp-jakarta + + + + org.apache.maven.plugins + maven-resources-plugin + + + copy-resources-assembly + prepare-package + + copy-resources + + + ${basedir}/target/webapp + + + ${basedir}/../frontend/target/webapp + false + + + + + + copy-sources + generate-sources + + copy-resources + + + ${project.build.directory}/generated-sources/jakarta + + + ${basedir}/../assembly/src/main/java + false + + + + + + copy-runtime + generate-resources + + copy-resources + + + ${jakarta.runtime} + + + ${basedir}/../assembly/src/main/runtime + true + + + + + + copy-webapp + generate-resources + + copy-resources + + + ${jakarta.webapp} + + + ${basedir}/../assembly/src/main/webapp + false + + + + + + copy-resources + generate-resources + + copy-resources + + + ${project.build.directory}/generated-resources/jakarta + + + ${basedir}/../assembly/src/main/resources + false + + + + + + copy-test-sources + generate-test-sources + + copy-resources + + + ${project.build.directory}/generated-test-sources/jakarta + + + ${basedir}/../assembly/src/test/java + false + + + + + + copy-test-resources + generate-test-resources + + copy-resources + + + ${project.build.directory}/generated-test-resources/jakarta + + + ${basedir}/../assembly/src/test/resources + true + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + initialize + + properties + + + + + + org.eclipse.transformer + transformer-maven-plugin + + + true + + ${project.basedir}/renames.properties + + + jakarta + + + + transform-sources + generate-sources + + transform + + + ${project.build.directory}/generated-sources/jakarta + + + + transform-runtime + generate-resources + + transform + + + ${jakarta.runtime} + + + + transform-webapp + generate-resources + + transform + + + ${jakarta.webapp} + + + + transform-jakarta-resources + generate-resources + + transform + + + ${project.build.directory}/generated-resources/jakarta + + + + transform-test-sources + generate-test-sources + + transform + + + ${project.build.directory}/generated-test-sources/jakarta + + + + transform-test-resources + generate-test-resources + + transform + + + ${project.build.directory}/generated-test-resources/jakarta + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.2.0 + + + add-jakarta-source + generate-sources + + add-source + + + + ${basedir}/target/generated-sources/jakarta + + + + + add-jakarta-resource + generate-resources + + add-resource + + + + + ${basedir}/target/generated-resources/jakarta + + + + + + add-jakarta-test-source + generate-test-sources + + add-test-source + + + + ${basedir}/target/generated-test-sources/jakarta + + + + + add-jakarta-test-resource + generate-test-resources + + add-test-resource + + + + + ${basedir}/target/generated-test-resources/jakarta + + + + + + + + + org.apache.maven.plugins + maven-war-plugin + + ${jakarta.webapp} + + + + maven-surefire-plugin + + false + false + true + + + + org.apache.maven.plugins + maven-jar-plugin + + + org.codehaus.mojo + license-maven-plugin + 1.14 + + test + + + + org.apache.maven.plugins + maven-assembly-plugin + + + org.apache.maven.plugins + maven-antrun-plugin + + + generate-resources + + + + + + + run + + + + + + + + + + central-sonatype-publish + + + true + + + + + os + + + Windows + + + + cmd + /c + + + + + develop + + + org.jboss.resteasy + resteasy-core + ${version.resteasy} + runtime + + + jakarta.ws.rs + jakarta.ws.rs-api + + + org.camunda.bpm + camunda-engine + + + org.camunda.bpm + camunda-engine-plugin-spin + + + org.camunda.spin + camunda-spin-dataformat-json-jackson + + + org.camunda.spin + camunda-spin-dataformat-xml-dom-jakarta + + + org.camunda.bpm + camunda-engine-plugin-connect + + + org.camunda.bpm.identity + camunda-identity-ldap + + + com.h2database + h2 + + + com.fasterxml.uuid + java-uuid-generator + + + ch.qos.logback + logback-classic + + + com.sun.xml.bind + jaxb-impl + ${version.xml.jaxb-impl4} + + + org.graalvm.js + js + + + org.graalvm.js + js-scriptengine + + + + + + org.eclipse.jetty + jetty-maven-plugin + + + /camunda + ${jakarta.runtime}/develop/jetty/webdefault.xml + + ${project.basedir}/target/webapp + ${jakarta.webapp} + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-sources + + add-source + + + + ${jakarta.runtime}/develop/java + + + + + add-resources + + add-resource + + + + + ${jakarta.runtime}/develop/resources + + + + + + + + + + ${jakarta.runtime}/develop/resources + + + + + h2 + + ./ + + + + + + cfghistoryaudit + + audit + + + + + + cfghistoryactivity + + activity + + + + + + cfghistorynone + + none + + + + + cfgJdbcBatchProcessingOff + + false + + + + + license-header-check + + + + com.mycila + license-maven-plugin + + + + + + + below-jdk17 + + (,17) + + + + + + maven-compiler-plugin + + + **/AuthCacheTest.java + **/ContainerAuthenticationFilterTest.java + **/CsrfPreventionFilterAppPathTest.java + **/CsrfPreventionFilterTest.java + **/UserAuthenticationResourceTest.java + **/UserAuthenticationResourceLoggingTest.java + + + + + + + + + jdk17-and-onwards + + [17,) + + + + ${version.spring.framework6} + + + + + org.springframework + spring-test + ${version.spring.framework} + test + + + + org.springframework + spring-web + ${version.spring.framework} + test + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly-jakarta/renames.properties b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly-jakarta/renames.properties new file mode 100644 index 0000000000000000000000000000000000000000..f2b6ffdd3209e6689bc03ed9d0feb53b816c1d22 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly-jakarta/renames.properties @@ -0,0 +1,14 @@ + +# DevProcessApplication +org.camunda.bpm.application.impl.ServletProcessApplication=org.camunda.bpm.application.impl.JakartaServletProcessApplication +ServletProcessApplication=JakartaServletProcessApplication + +# H2 +org.h2.server.web.WebServlet=org.h2.server.web.JakartaWebServlet + +# References to resources from tests +src/main/webapp/WEB-INF/securityFilterRules.json=target/generated-resources/jakarta-webapp/WEB-INF/securityFilterRules.json +src/test/resources/WEB-INF/=target/generated-test-resources/jakarta/WEB-INF/ + +# Logging +javax.activation.level=jakarta.activation.level \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/main/webapp/develop/invoice-forms/start-form.html b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/main/webapp/develop/invoice-forms/start-form.html new file mode 100644 index 0000000000000000000000000000000000000000..9cdedb9afbd7951916dd2c28372576956d901853 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/main/webapp/develop/invoice-forms/start-form.html @@ -0,0 +1,117 @@ +
+ +
Please fill in the details for the invoice you received
+ + +
+ +
+ +
This field is required
+
+
+ + + + +
+ +
+ +
+ (e.g. "Great Pizza for Everyone Inc.") +
+
+
+ + +
+ +
+ +
+ (e.g. "30.00") +
+ +

+ Note: Input must be a 'Double'. +

+ +
+
+ + +
+ +
+ + +
+
+ + +
+ +
+ +
+ (e.g. "I-12345") +
+
+
+ +
+ diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/main/webapp/error-404-page.html b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/main/webapp/error-404-page.html new file mode 100644 index 0000000000000000000000000000000000000000..041baad061cee74bfb7b1fb706709ba312dde35f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/main/webapp/error-404-page.html @@ -0,0 +1,131 @@ + + + + + + Camunda - Not Found + + + + +
+
+
+

Not Found (404)

+
+

The Page you are requesting was not found on this server.

+

Try going back to the Front Page and attempting the Action again.

+
+
+ + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/main/webapp/error-500-page.html b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/main/webapp/error-500-page.html new file mode 100644 index 0000000000000000000000000000000000000000..2a5d1049be2d774e8244f6b9ca05355e180dc680 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/main/webapp/error-500-page.html @@ -0,0 +1,132 @@ + + + + + + Camunda - Internal Server Error + + + + +
+
+
+

Internal Server Error (500)

+
+

An error occurred while processing your request.

+

Try reloading the Page, or going back and attempting the action again.

+
+ + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/main/webapp/index.html b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/main/webapp/index.html new file mode 100644 index 0000000000000000000000000000000000000000..2a5381f81f3f3f9cad2b655ed0c0f0600c90a82c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/main/webapp/index.html @@ -0,0 +1,11 @@ + + + + Camunda Welcome + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/admin/plugin/base/AbstractAdminPluginTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/admin/plugin/base/AbstractAdminPluginTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f1be3c2fee7a6ac162da91cf35d3e5ef7780582b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/admin/plugin/base/AbstractAdminPluginTest.java @@ -0,0 +1,79 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.admin.plugin.base; + +import org.apache.ibatis.logging.LogFactory; +import org.camunda.bpm.admin.Admin; +import org.camunda.bpm.admin.impl.DefaultAdminRuntimeDelegate; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.util.LogUtil; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; + +public abstract class AbstractAdminPluginTest { + + protected static final TestAdminRuntimeDelegate RUNTIME_DELEGATE = new TestAdminRuntimeDelegate(); + + static { + LogUtil.readJavaUtilLoggingConfigFromClasspath(); + LogFactory.useJdkLogging(); + } + + @Rule + public ProcessEngineRule processEngineRule = new ProcessEngineRule(true); + + @BeforeClass + public static void beforeClass() { + Admin.setAdminRuntimeDelegate(RUNTIME_DELEGATE); + } + + @AfterClass + public static void afterClass() { + Admin.setAdminRuntimeDelegate(null); + } + + @Before + public void before() { + RUNTIME_DELEGATE.ENGINE = getProcessEngine(); + } + + @After + public void after() { + RUNTIME_DELEGATE.ENGINE = null; + getProcessEngine().getIdentityService().clearAuthentication(); + } + + public ProcessEngine getProcessEngine() { + return processEngineRule.getProcessEngine(); + } + + private static class TestAdminRuntimeDelegate extends DefaultAdminRuntimeDelegate { + + public ProcessEngine ENGINE; + + @Override + public ProcessEngine getProcessEngine(String processEngineName) { + + // always return default engine for plugin tests + return ENGINE; + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/admin/plugin/base/MetricsRestServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/admin/plugin/base/MetricsRestServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..449d0d52c6f49f188e1d225fae67098456e5a530 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/admin/plugin/base/MetricsRestServiceTest.java @@ -0,0 +1,488 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.admin.plugin.base; + +import org.assertj.core.groups.Tuple; +import org.camunda.bpm.admin.impl.plugin.resources.MetricsRestService; +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.metrics.MetricsRegistry; +import org.camunda.bpm.engine.impl.metrics.reporter.DbMetricsReporter; +import org.camunda.bpm.engine.impl.persistence.entity.TaskMeterLogEntity; +import org.camunda.bpm.engine.impl.util.ClockUtil; +import org.camunda.bpm.engine.management.Metrics; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.joda.time.DateTime; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; +import java.util.ArrayList; +import java.util.UUID; +import java.util.function.Consumer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.tuple; + +public class MetricsRestServiceTest extends AbstractAdminPluginTest { + + private final MultivaluedMap queryParameters = new MultivaluedHashMap<>(); + private MetricsRestService resource; + private UriInfo uriInfo; + private ManagementService managementService; + private DbMetricsReporter dbMetricsReporter; + private MetricsRegistry metricsRegistry; + + @Before + public void setUp() throws Exception { + super.before(); + + var processEngine = getProcessEngine(); + var processEngineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration(); + dbMetricsReporter = processEngineConfiguration.getDbMetricsReporter(); + metricsRegistry = processEngineConfiguration.getMetricsRegistry(); + managementService = processEngine.getManagementService(); + + resource = new MetricsRestService(processEngine.getName()); + + uriInfo = Mockito.mock(UriInfo.class); + Mockito.doReturn(queryParameters).when(uriInfo).getQueryParameters(); + } + + @After + public void tearDown() { + queryParameters.clear(); + managementService.deleteMetrics(null); + managementService.deleteTaskMetrics(null); + ClockUtil.reset(); + } + + @Test + public void shouldThrowExceptionWhenSubscriptionStartDateNotProvided() { + // given + queryParameters.add("subscriptionStartDate", ""); + + // when + assertThatThrownBy(() -> resource.getAggregatedMetrics(uriInfo)) + // then + .isInstanceOf(InvalidRequestException.class) + .hasMessage("subscriptionStartDate parameter has invalid value: null"); + } + + @Test + public void shouldThrowExceptionWhenSubscriptionStartDateInvalid() { + // given + queryParameters.add("subscriptionStartDate", "notDate"); + queryParameters.add("groupBy", "month"); + + // when + assertThatThrownBy(() -> resource.getAggregatedMetrics(uriInfo)) + // then + .isInstanceOf(InvalidRequestException.class) + .hasMessage( + "Cannot set query parameter 'subscriptionStartDate' to value 'notDate': Cannot convert value \"notDate\" to java type java.util.Date"); + } + + @Test + public void shouldThrowExceptionWhenSubscriptionStartDateNotInPast() { + // given + queryParameters.add("subscriptionStartDate", new DateTime().withYear(2100).withMonthOfYear(1).withDayOfMonth(31).toString()); + queryParameters.add("groupBy", "month"); + + // when + assertThatThrownBy(() -> resource.getAggregatedMetrics(uriInfo)) + // then + .isInstanceOf(InvalidRequestException.class) + .hasMessageStartingWith("subscriptionStartDate parameter has invalid value: Sun Jan 31"); + } + + @Test + public void shouldThrowExceptionWhenGroupByNotProvided() { + // given + queryParameters.add("subscriptionStartDate", "2024-01-01"); + + // when + assertThatThrownBy(() -> resource.getAggregatedMetrics(uriInfo)) + // then + .isInstanceOf(InvalidRequestException.class).hasMessage("groupBy parameter has invalid value: null"); + } + + @Test + public void shouldThrowExceptionWhenGroupByInvalid() { + // given + queryParameters.add("subscriptionStartDate", "2024-01-01"); + queryParameters.add("groupBy", "day"); + + // when + assertThatThrownBy(() -> resource.getAggregatedMetrics(uriInfo)) + // then + .isInstanceOf(InvalidRequestException.class).hasMessage("groupBy parameter has invalid value: day"); + } + + @Test + public void shouldThrowExceptionWhenStartDateInvalid() { + // given + queryParameters.add("subscriptionStartDate", "2024-01-01"); + queryParameters.add("startDate", "notDate"); + + // when + assertThatThrownBy(() -> resource.getAggregatedMetrics(uriInfo)) + // then + .isInstanceOf(InvalidRequestException.class) + .hasMessage( + "Cannot set query parameter 'startDate' to value 'notDate': Cannot convert value \"notDate\" to java type java.util.Date"); + } + + @Test + public void shouldThrowExceptionWhenEndDateInvalid() { + // given + queryParameters.add("subscriptionStartDate", "2024-01-01"); + queryParameters.add("endDate", "notDate"); + + // when + assertThatThrownBy(() -> resource.getAggregatedMetrics(uriInfo)) + // then + .isInstanceOf(InvalidRequestException.class) + .hasMessage( + "Cannot set query parameter 'endDate' to value 'notDate': Cannot convert value \"notDate\" to java type java.util.Date"); + } + + @Test + public void shouldThrowExceptionWhenStartDateNotBeforeEndDate() { + // given + queryParameters.add("subscriptionStartDate", "2024-01-01"); + queryParameters.add("startDate", "2023-01-31T16:54:00.000+0100"); + queryParameters.add("endDate", "2023-01-31T16:54:00.000+0100"); + + // when + assertThatThrownBy(() -> resource.getAggregatedMetrics(uriInfo)) + // then + .isInstanceOf(InvalidRequestException.class).hasMessage("endDate parameter must be after startDate"); + } + + @Test + public void shouldThrowExceptionWhenMetricsInvalid() { + // given + queryParameters.add("subscriptionStartDate", "2024-01-01"); + queryParameters.add("groupBy", "month"); + queryParameters.add("metrics", "a,process-instances"); + + // when + assertThatThrownBy(() -> resource.getAggregatedMetrics(uriInfo)) + // then + .isInstanceOf(InvalidRequestException.class) + .hasMessage("Cannot set query parameter 'metrics' to value 'a,process-instances'"); + } + + @Test + public void shouldReturnAggregatedMetricsFilteredByMetricsParameter() { + // given + queryParameters.add("subscriptionStartDate", new DateTime().withYear(2020).withMonthOfYear(1).withDayOfMonth(1).toString()); + queryParameters.add("groupBy", "year"); + queryParameters.add("metrics", String.format("%s,%s", Metrics.PROCESS_INSTANCES, Metrics.FLOW_NODE_INSTANCES)); + + // generate metrics for all available meters + var metricNames = metricsRegistry.getDbMeters().keySet(); + metricNames.forEach(metric -> metricsRegistry.markOccurrence(metric, 1)); + dbMetricsReporter.reportNow(); + + // when + var actual = resource.getAggregatedMetrics(uriInfo); + + // then - only the two selected metrics are returned + assertThat(actual).hasSize(2); + assertThat(actual).extracting("metric", "sum", "subscriptionYear", "subscriptionMonth") + .containsExactlyInAnyOrder( + tuple(Metrics.PROCESS_INSTANCES, 1L, new DateTime().getYear(), null), + tuple(Metrics.FLOW_NODE_INSTANCES, 1L, new DateTime().getYear(), null)); + } + + @Test + public void shouldReturnAggregatedMetricsFilteredByStartDateParameter() { + // given + queryParameters.add("subscriptionStartDate", new DateTime().withYear(2020).withMonthOfYear(1).withDayOfMonth(1).toString()); + queryParameters.add("groupBy", "year"); + queryParameters.add("startDate", "2022-01-01"); + queryParameters.add("metrics", Metrics.PROCESS_INSTANCES); + + // generate metrics for 2021 and current year + var dateTime = new DateTime().withYear(2021); + ClockUtil.setCurrentTime(dateTime.toDate()); + metricsRegistry.markOccurrence(Metrics.ROOT_PROCESS_INSTANCE_START, 1); + dbMetricsReporter.reportNow(); + ClockUtil.reset(); + metricsRegistry.markOccurrence(Metrics.ROOT_PROCESS_INSTANCE_START, 1); + dbMetricsReporter.reportNow(); + + // when + var actual = resource.getAggregatedMetrics(uriInfo); + + // then - the metric from 2021 is not returned + assertThat(actual).hasSize(1); + assertThat(actual).extracting("metric", "sum", "subscriptionYear", "subscriptionMonth") + .containsExactly( + tuple(Metrics.PROCESS_INSTANCES, 1L, new DateTime().getYear(), null)); + } + + @Test + public void shouldReturnAggregatedMetricsFilteredByEndDateParameter() { + // given + queryParameters.add("subscriptionStartDate", new DateTime().withYear(2020).withMonthOfYear(1).withDayOfMonth(1).toString()); + queryParameters.add("groupBy", "year"); + queryParameters.add("endDate", "2022-01-01"); + queryParameters.add("metrics", Metrics.PROCESS_INSTANCES); + + // generate metrics for 2021 and current year + var dateTime = new DateTime().withYear(2021); + ClockUtil.setCurrentTime(dateTime.toDate()); + metricsRegistry.markOccurrence(Metrics.ROOT_PROCESS_INSTANCE_START, 1); + dbMetricsReporter.reportNow(); + ClockUtil.reset(); + metricsRegistry.markOccurrence(Metrics.ROOT_PROCESS_INSTANCE_START, 1); + dbMetricsReporter.reportNow(); + + // when + var actual = resource.getAggregatedMetrics(uriInfo); + + // then - the metric from current year is not returned + assertThat(actual).hasSize(1); + assertThat(actual).extracting("metric", "sum", "subscriptionYear", "subscriptionMonth") + .containsExactly( + tuple(Metrics.PROCESS_INSTANCES, 1L, dateTime.getYear(), null)); + } + + @Test + public void shouldReturnAggregatedMetricsGroupedByMonth() { + // given + queryParameters.add("subscriptionStartDate", new DateTime().withYear(2020).withMonthOfYear(4).withDayOfMonth(15).toString()); + queryParameters.add("groupBy", "month"); + queryParameters.add("metrics", Metrics.PROCESS_INSTANCES); + + // generate metrics for 2021-02-15T00:00:00.000+01:00 & 2021-02-14T23:59:59.999+01:00 + var dateTime = new DateTime().withYear(2021) + .withMonthOfYear(2) + .withDayOfMonth(15) + .withTimeAtStartOfDay() + .minusMillis(1); + ClockUtil.setCurrentTime(dateTime.toDate()); + metricsRegistry.markOccurrence(Metrics.ROOT_PROCESS_INSTANCE_START, 1); + dbMetricsReporter.reportNow(); + dateTime = dateTime.withDayOfMonth(15).withTimeAtStartOfDay(); + ClockUtil.setCurrentTime(dateTime.toDate()); + metricsRegistry.markOccurrence(Metrics.ROOT_PROCESS_INSTANCE_START, 1); + dbMetricsReporter.reportNow(); + ClockUtil.reset(); + + // when + var actual = resource.getAggregatedMetrics(uriInfo); + + // then - metrics are grouped by months (Jan, Feb) with respect to the subscriptionStartDate + assertThat(actual).hasSize(2); + assertThat(actual).extracting("metric", "sum", "subscriptionYear", "subscriptionMonth") + .containsExactlyInAnyOrder( + tuple(Metrics.PROCESS_INSTANCES, 1L, dateTime.getYear(), 2), + tuple(Metrics.PROCESS_INSTANCES, 1L, dateTime.getYear(), 1)); + } + + @Test + public void shouldReturnAggregatedMetricsGroupedByYear() { + // given + queryParameters.add("subscriptionStartDate", new DateTime().withYear(2020).withMonthOfYear(4).withDayOfMonth(15).toString()); + queryParameters.add("groupBy", "year"); + queryParameters.add("metrics", Metrics.PROCESS_INSTANCES); + + // generate metrics for 2021-04-15T00:00:00.000+01:00 & 2021-04-14T23:59:59.999+01:00 + var dateTime = new DateTime().withYear(2021) + .withMonthOfYear(4) + .withDayOfMonth(15) + .withTimeAtStartOfDay() + .minusMillis(1); + ClockUtil.setCurrentTime(dateTime.toDate()); + metricsRegistry.markOccurrence(Metrics.ROOT_PROCESS_INSTANCE_START, 1); + dbMetricsReporter.reportNow(); + dateTime = dateTime.withDayOfMonth(15).withTimeAtStartOfDay(); + ClockUtil.setCurrentTime(dateTime.toDate()); + metricsRegistry.markOccurrence(Metrics.ROOT_PROCESS_INSTANCE_START, 1); + dbMetricsReporter.reportNow(); + ClockUtil.reset(); + + // when + var actual = resource.getAggregatedMetrics(uriInfo); + + // then - metrics are grouped by years (2020, 2021) with respect to the subscriptionStartDate + assertThat(actual).hasSize(2); + assertThat(actual).extracting("metric", "sum", "subscriptionYear", "subscriptionMonth") + .containsExactlyInAnyOrder( + tuple(Metrics.PROCESS_INSTANCES, 1L, dateTime.getYear(), null), + tuple(Metrics.PROCESS_INSTANCES, 1L, dateTime.minusYears(1).getYear(), null)); + } + + @Test + public void shouldReturnAnnualAggregatedMetricsForTU() { + // given + queryParameters.add("subscriptionStartDate", new DateTime().withYear(2020).withMonthOfYear(1).withDayOfMonth(1).toString()); + queryParameters.add("groupBy", "year"); + queryParameters.add("metrics", Metrics.TASK_USERS); + + // generate TU metric - counts _unique_ task workers (unique ASSIGNEE_HASH_) + processEngineRule.getProcessEngineConfiguration().getCommandExecutorTxRequired().execute(commandContext -> { + commandContext.getMeterLogManager().insert(new TaskMeterLogEntity("assignee", ClockUtil.getCurrentTime())); + commandContext.getMeterLogManager().insert(new TaskMeterLogEntity("assignee", ClockUtil.getCurrentTime())); + ClockUtil.reset(); + return null; + }); + + // when + var actual = resource.getAggregatedMetrics(uriInfo); + + // then + assertThat(actual).hasSize(1); + assertThat(actual).extracting("metric", "sum", "subscriptionYear", "subscriptionMonth") + .containsExactly( + tuple(Metrics.TASK_USERS, 1L, new DateTime().getYear(), null)); + } + + @Test + public void shouldReturnMonthlyAggregatedMetricsForTU() { + // given + queryParameters.add("subscriptionStartDate", new DateTime().withYear(2020).withMonthOfYear(1).withDayOfMonth(1).toString()); + queryParameters.add("startDate", "2023-01-01"); + queryParameters.add("groupBy", "month"); + queryParameters.add("metrics", Metrics.TASK_USERS); + + // generate TU metric - counts _unique_ task workers (unique ASSIGNEE_HASH_) for the selected period (startDate, endDate) + DateTime now = new DateTime(); + DateTime prevMonth = now.minusMonths(1); + processEngineRule.getProcessEngineConfiguration().getCommandExecutorTxRequired().execute(commandContext -> { + commandContext.getMeterLogManager().insert(new TaskMeterLogEntity("assignee1", ClockUtil.getCurrentTime())); + commandContext.getMeterLogManager().insert(new TaskMeterLogEntity("assignee3", ClockUtil.getCurrentTime())); + + ClockUtil.setCurrentTime(prevMonth.toDate()); + commandContext.getMeterLogManager().insert(new TaskMeterLogEntity("assignee1", ClockUtil.getCurrentTime())); + commandContext.getMeterLogManager().insert(new TaskMeterLogEntity("assignee2", ClockUtil.getCurrentTime())); + + ClockUtil.setCurrentTime(now.withYear(2022).toDate()); + commandContext.getMeterLogManager().insert(new TaskMeterLogEntity("assignee1", ClockUtil.getCurrentTime())); + ClockUtil.reset(); + return null; + }); + + // when + var actual = resource.getAggregatedMetrics(uriInfo); + + // then + assertThat(actual).hasSize(2); + assertThat(actual).extracting("metric", "sum", "subscriptionYear", "subscriptionMonth") + .containsExactlyInAnyOrder( + tuple(Metrics.TASK_USERS, 1L, now.getYear(), now.getMonthOfYear()), + tuple(Metrics.TASK_USERS, 2L, prevMonth.getYear(), prevMonth.getMonthOfYear())); + } + + protected void generateMetrics(int year, int month, int times) { + var dateTime = new DateTime().withYear(year).withMonthOfYear(month).withDayOfMonth(10); + + for (int i = 1; i <= times; i++) { + ClockUtil.setCurrentTime(dateTime.toDate()); + + metricsRegistry.markOccurrence(Metrics.ROOT_PROCESS_INSTANCE_START, i); + metricsRegistry.markOccurrence(Metrics.ACTIVTY_INSTANCE_START, i); + metricsRegistry.markOccurrence(Metrics.EXECUTED_DECISION_INSTANCES, i); + metricsRegistry.markOccurrence(Metrics.EXECUTED_DECISION_ELEMENTS, i); + dbMetricsReporter.reportNow(); + + int i1 = i; + processEngineRule.getProcessEngineConfiguration().getCommandExecutorTxRequired().execute(commandContext -> { + for (int j = 1; j <= i1; j++) { + commandContext.getMeterLogManager().insert( + new TaskMeterLogEntity(UUID.randomUUID().toString(), ClockUtil.getCurrentTime())); + } + return null; + }); + + dateTime = dateTime.minusDays(1); + } + ClockUtil.reset(); + } + + @Test + public void shouldReturnAggregatedMetricsByYear() { + // given + queryParameters.add("subscriptionStartDate", new DateTime().withYear(2020).withMonthOfYear(1).withDayOfMonth(1).toString()); + queryParameters.add("groupBy", "year"); + + // generate metrics for last 5 days & last 3 years + generateMetrics(2024, 2, 2); + generateMetrics(2023, 2, 3); + + // when + var actual = resource.getAggregatedMetrics(uriInfo); + + // then + assertThat(actual).hasSize(10); + // generate tuples + var tuples = new ArrayList(); + Consumer generateAssertTuple = (String metric) -> { + tuples.add(tuple(metric, 3L, 2024, null)); + tuples.add(tuple(metric, 6L, 2023, null)); + }; + generateAssertTuple.accept(Metrics.PROCESS_INSTANCES); + generateAssertTuple.accept(Metrics.FLOW_NODE_INSTANCES); + generateAssertTuple.accept(Metrics.DECISION_INSTANCES); + generateAssertTuple.accept(Metrics.EXECUTED_DECISION_ELEMENTS); + generateAssertTuple.accept(Metrics.TASK_USERS); + + assertThat(actual).extracting("metric", "sum", "subscriptionYear", "subscriptionMonth") + .containsExactlyInAnyOrder(tuples.toArray(new Tuple[]{})); + } + + @Test + public void shouldReturnAggregatedMetricsByMonth() { + // given + queryParameters.add("subscriptionStartDate", new DateTime().withYear(2020).withMonthOfYear(1).withDayOfMonth(1).toString()); + queryParameters.add("groupBy", "month"); + + // generate metrics for last 5 days & last 3 years + generateMetrics(2024, 2, 2); + generateMetrics(2024, 1, 3); + + // when + var actual = resource.getAggregatedMetrics(uriInfo); + + // then + assertThat(actual).hasSize(10); + // generate tuples + var tuples = new ArrayList(); + Consumer generateAssertTuple = (String metric) -> { + tuples.add(tuple(metric, 3L, 2024, 2)); + tuples.add(tuple(metric, 6L, 2024, 1)); + }; + generateAssertTuple.accept(Metrics.PROCESS_INSTANCES); + generateAssertTuple.accept(Metrics.FLOW_NODE_INSTANCES); + generateAssertTuple.accept(Metrics.DECISION_INSTANCES); + generateAssertTuple.accept(Metrics.EXECUTED_DECISION_ELEMENTS); + generateAssertTuple.accept(Metrics.TASK_USERS); + + assertThat(actual).extracting("metric", "sum", "subscriptionYear", "subscriptionMonth") + .containsExactlyInAnyOrder(tuples.toArray(new Tuple[]{})); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/IncidentRestServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/IncidentRestServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ad25963811b500d67e49ae4f3d83eecc2b958bd1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/IncidentRestServiceTest.java @@ -0,0 +1,533 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base; + +import static junit.framework.TestCase.fail; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.IncidentDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.query.IncidentQueryDto; +import org.camunda.bpm.cockpit.impl.plugin.resources.IncidentRestService; +import org.camunda.bpm.cockpit.plugin.test.AbstractCockpitPluginTest; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.runtime.Incident; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.test.Deployment; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * @author roman.smirnov + */ +public class IncidentRestServiceTest extends AbstractCockpitPluginTest { + + private ProcessEngine processEngine; + protected ProcessEngineConfigurationImpl processEngineConfiguration; + private RepositoryService repositoryService; + private RuntimeService runtimeService; + private IncidentRestService resource; + protected IdentityService identityService; + + @Before + public void setUp() throws Exception { + super.before(); + + processEngine = getProcessEngine(); + processEngineConfiguration = (ProcessEngineConfigurationImpl) processEngine + .getProcessEngineConfiguration(); + repositoryService = processEngine.getRepositoryService(); + runtimeService = processEngine.getRuntimeService(); + identityService = processEngine.getIdentityService(); + + resource = new IncidentRestService(processEngine.getName()); + } + + @After + public void clearAuthentication() { + identityService.clearAuthentication(); + } + + @After + public void resetQueryMaxResultsLimit() { + processEngineConfiguration.setQueryMaxResultsLimit(Integer.MAX_VALUE); + } + + @Test + @Deployment(resources = { + "processes/failing-process.bpmn" + }) + public void testQueryByProcessInstanceId() { + ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("FailingProcess"); + runtimeService.startProcessInstanceByKey("FailingProcess"); + + executeAvailableJobs(); + + String incidentId = runtimeService.createIncidentQuery().processInstanceId(processInstance1.getId()).singleResult().getId(); + + runtimeService.setAnnotationForIncidentById(incidentId, "an Annotation"); + + String[] processInstanceIds= {processInstance1.getId()}; + + IncidentQueryDto queryParameter = new IncidentQueryDto(); + queryParameter.setProcessInstanceIdIn(processInstanceIds); + + List result = resource.queryIncidents(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + IncidentDto incident = result.get(0); + + assertThat(incident.getId()).isNotNull(); + assertThat(incident.getIncidentType()).isEqualTo(Incident.FAILED_JOB_HANDLER_TYPE); + assertThat(incident.getIncidentMessage()).isEqualTo("I am failing!"); + assertThat(incident.getIncidentTimestamp()).isNotNull(); + assertThat(incident.getActivityId()).isEqualTo("ServiceTask_1"); + assertThat(incident.getFailedActivityId()).isEqualTo("ServiceTask_1"); + assertThat(incident.getProcessInstanceId()).isEqualTo(processInstance1.getId()); + assertThat(incident.getProcessDefinitionId()).isEqualTo(processInstance1.getProcessDefinitionId()); + assertThat(incident.getExecutionId()).isEqualTo(processInstance1.getId()); + assertThat(incident.getConfiguration()).isNotNull(); + assertThat(incident.getAnnotation()).isEqualTo("an Annotation"); + assertThat(incident.getCauseIncidentId()).isEqualTo(incident.getId()); + assertThat(incident.getCauseIncidentProcessInstanceId()).isEqualTo(processInstance1.getId()); + assertThat(incident.getCauseIncidentProcessDefinitionId()).isEqualTo(processInstance1.getProcessDefinitionId()); + assertThat(incident.getCauseIncidentActivityId()).isEqualTo("ServiceTask_1"); + assertThat(incident.getCauseIncidentFailedActivityId()).isEqualTo("ServiceTask_1"); + assertThat(incident.getRootCauseIncidentId()).isEqualTo(incident.getId()); + assertThat(incident.getRootCauseIncidentProcessInstanceId()).isEqualTo(processInstance1.getId()); + assertThat(incident.getRootCauseIncidentProcessDefinitionId()).isEqualTo(processInstance1.getProcessDefinitionId()); + assertThat(incident.getRootCauseIncidentActivityId()).isEqualTo("ServiceTask_1"); + assertThat(incident.getRootCauseIncidentFailedActivityId()).isEqualTo("ServiceTask_1"); + assertThat(incident.getRootCauseIncidentConfiguration()).isNotNull(); + assertThat(incident.getRootCauseIncidentMessage()).isEqualTo("I am failing!"); + } + + @Test + @Deployment(resources = { + "processes/failing-process.bpmn" + }) + public void testQueryByProcessInstanceIds() { + ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("FailingProcess"); + ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("FailingProcess"); + + executeAvailableJobs(); + + String[] processInstanceIds= {processInstance1.getId(), processInstance2.getId()}; + + IncidentQueryDto queryParameter = new IncidentQueryDto(); + queryParameter.setProcessInstanceIdIn(processInstanceIds); + + List result = resource.queryIncidents(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + } + + @Test + @Deployment(resources = { + "processes/process-with-two-parallel-failing-services.bpmn" + }) + public void testQueryByActivityId() { + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("processWithTwoParallelFailingServices"); + + executeAvailableJobs(); + + String[] activityIds= {"theServiceTask1"}; + + IncidentQueryDto queryParameter = new IncidentQueryDto(); + queryParameter.setActivityIdIn(activityIds); + + List result = resource.queryIncidents(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + IncidentDto incident = result.get(0); + + assertThat(incident.getId()).isNotNull(); + assertThat(incident.getIncidentType()).isEqualTo(Incident.FAILED_JOB_HANDLER_TYPE); + assertThat(incident.getIncidentMessage()).isEqualTo("I am failing!"); + assertThat(incident.getIncidentTimestamp()).isNotNull(); + assertThat(incident.getActivityId()).isEqualTo("theServiceTask1"); + assertThat(incident.getFailedActivityId()).isEqualTo("theServiceTask1"); + assertThat(incident.getProcessInstanceId()).isEqualTo(processInstance.getId()); + assertThat(incident.getProcessDefinitionId()).isEqualTo(processInstance.getProcessDefinitionId()); + assertThat(incident.getExecutionId()).isNotNull(); + assertThat(incident.getConfiguration()).isNotNull(); + assertThat(incident.getCauseIncidentId()).isEqualTo(incident.getId()); + assertThat(incident.getCauseIncidentProcessInstanceId()).isEqualTo(processInstance.getId()); + assertThat(incident.getCauseIncidentProcessDefinitionId()).isEqualTo(processInstance.getProcessDefinitionId()); + assertThat(incident.getCauseIncidentActivityId()).isEqualTo("theServiceTask1"); + assertThat(incident.getCauseIncidentFailedActivityId()).isEqualTo("theServiceTask1"); + assertThat(incident.getRootCauseIncidentId()).isEqualTo(incident.getId()); + assertThat(incident.getRootCauseIncidentProcessInstanceId()).isEqualTo(processInstance.getId()); + assertThat(incident.getRootCauseIncidentProcessDefinitionId()).isEqualTo(processInstance.getProcessDefinitionId()); + assertThat(incident.getRootCauseIncidentActivityId()).isEqualTo("theServiceTask1"); + assertThat(incident.getRootCauseIncidentFailedActivityId()).isEqualTo("theServiceTask1"); + assertThat(incident.getRootCauseIncidentConfiguration()).isNotNull(); + assertThat(incident.getRootCauseIncidentMessage()).isEqualTo("I am failing!"); + } + + @Test + @Deployment(resources = { + "processes/process-with-two-parallel-failing-services.bpmn" + }) + public void testQueryByActivityIds() { + runtimeService.startProcessInstanceByKey("processWithTwoParallelFailingServices"); + + executeAvailableJobs(); + + String[] activityIds= {"theServiceTask1", "theServiceTask2"}; + + IncidentQueryDto queryParameter = new IncidentQueryDto(); + queryParameter.setActivityIdIn(activityIds); + + List result = resource.queryIncidents(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + } + + @Test + @Deployment(resources = { + "processes/failing-process.bpmn" + }) + public void testQueryByProcessInstanceIdAndActivityId() { + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("FailingProcess"); + + executeAvailableJobs(); + + String[] processInstanceIds= {processInstance.getId()}; + String[] activityIds= {"ServiceTask_1"}; + + IncidentQueryDto queryParameter = new IncidentQueryDto(); + queryParameter.setProcessInstanceIdIn(processInstanceIds); + queryParameter.setActivityIdIn(activityIds); + + List result = resource.queryIncidents(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + } + + @Test + @Deployment(resources = { + "processes/failing-process.bpmn", + "processes/process-with-two-parallel-failing-services.bpmn" + }) + public void testQueryByProcessInstanceIdAndActivityId_ShouldReturnEmptyList() { + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("FailingProcess"); + runtimeService.startProcessInstanceByKey("processWithTwoParallelFailingServices"); + + executeAvailableJobs(); + + String[] processInstanceIds= {processInstance.getId()}; + String[] activityIds= {"theServiceTask1"}; // is an activity id in "processWithTwoParallelFailingServices" + + IncidentQueryDto queryParameter = new IncidentQueryDto(); + queryParameter.setProcessInstanceIdIn(processInstanceIds); + queryParameter.setActivityIdIn(activityIds); + + List result = resource.queryIncidents(queryParameter, null, null); + + assertThat(result).isEmpty(); + } + + @Test + @Deployment(resources = { + "processes/failing-process.bpmn", + "processes/call-activity.bpmn", + "processes/nested-call-activity.bpmn" + }) + public void testQueryWithNestedIncidents() { + ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("NestedCallActivity"); + + executeAvailableJobs(); + + ProcessInstance processInstance2 = runtimeService.createProcessInstanceQuery().processDefinitionKey("CallActivity").singleResult(); + ProcessInstance processInstance3 = runtimeService.createProcessInstanceQuery().processDefinitionKey("FailingProcess").singleResult(); + + String[] processInstanceIds= {processInstance1.getId()}; + + IncidentQueryDto queryParameter = new IncidentQueryDto(); + queryParameter.setProcessInstanceIdIn(processInstanceIds); + + List result = resource.queryIncidents(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + IncidentDto incident = result.get(0); + + assertThat(incident.getId()).isNotNull(); + assertThat(incident.getIncidentType()).isEqualTo(Incident.FAILED_JOB_HANDLER_TYPE); + assertThat(incident.getIncidentMessage()).isNull(); + assertThat(incident.getIncidentTimestamp()).isNotNull(); + assertThat(incident.getActivityId()).isEqualTo("CallActivity_1"); + assertThat(incident.getFailedActivityId()).isEqualTo("CallActivity_1"); + assertThat(incident.getProcessInstanceId()).isEqualTo(processInstance1.getId()); + assertThat(incident.getProcessDefinitionId()).isEqualTo(processInstance1.getProcessDefinitionId()); + assertThat(incident.getExecutionId()).isNotNull(); + assertThat(incident.getConfiguration()).isNull(); + + assertThat(incident.getCauseIncidentId()).isNotEqualTo(incident.getId()); + assertThat(incident.getCauseIncidentProcessInstanceId()).isEqualTo(processInstance2.getId()); + assertThat(incident.getCauseIncidentProcessDefinitionId()).isEqualTo(processInstance2.getProcessDefinitionId()); + assertThat(incident.getCauseIncidentActivityId()).isEqualTo("CallActivity_1"); + assertThat(incident.getCauseIncidentFailedActivityId()).isEqualTo("CallActivity_1"); + + assertThat(incident.getRootCauseIncidentId()).isNotEqualTo(incident.getId()); + assertThat(incident.getRootCauseIncidentProcessInstanceId()).isEqualTo(processInstance3.getId()); + assertThat(incident.getRootCauseIncidentProcessDefinitionId()).isEqualTo(processInstance3.getProcessDefinitionId()); + assertThat(incident.getRootCauseIncidentActivityId()).isEqualTo("ServiceTask_1"); + assertThat(incident.getRootCauseIncidentFailedActivityId()).isEqualTo("ServiceTask_1"); + assertThat(incident.getRootCauseIncidentConfiguration()).isNotNull(); + assertThat(incident.getRootCauseIncidentMessage()).isEqualTo("I am failing!"); + } + + @Test + @Deployment(resources = { + "processes/process-with-two-parallel-failing-services.bpmn" + }) + public void testQueryPaginiation() { + runtimeService.startProcessInstanceByKey("processWithTwoParallelFailingServices"); + + executeAvailableJobs(); + + IncidentQueryDto queryParameter = new IncidentQueryDto(); + + List result = resource.queryIncidents(queryParameter, 0, 2); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + result = resource.queryIncidents(queryParameter, 2, 1); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + result = resource.queryIncidents(queryParameter, 4, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(6); + + result = resource.queryIncidents(queryParameter, null, 4); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(4); + } + + @Test + @Deployment(resources = { + "processes/failing-process.bpmn", + "processes/call-activity.bpmn", + "processes/nested-call-activity.bpmn" + }) + public void testQueryByProcessDefinitionId() { + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("NestedCallActivity"); + + executeAvailableJobs(); + + String[] processDefinitionIds = { processInstance.getProcessDefinitionId() }; + + IncidentQueryDto queryParameter = new IncidentQueryDto(); + queryParameter.setProcessDefinitionIdIn(processDefinitionIds); + + List result = resource.queryIncidents(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + IncidentDto incident = result.get(0); + + assertThat(incident.getId()).isNotNull(); + assertThat(incident.getIncidentType()).isEqualTo(Incident.FAILED_JOB_HANDLER_TYPE); + assertThat(incident.getIncidentMessage()).isNull(); + assertThat(incident.getIncidentTimestamp()).isNotNull(); + assertThat(incident.getActivityId()).isEqualTo("CallActivity_1"); + assertThat(incident.getFailedActivityId()).isEqualTo("CallActivity_1"); + assertThat(incident.getProcessInstanceId()).isEqualTo(processInstance.getId()); + assertThat(incident.getProcessDefinitionId()).isEqualTo(processInstance.getProcessDefinitionId()); + assertThat(incident.getExecutionId()).isNotNull(); + assertThat(incident.getConfiguration()).isNull(); + } + + @Test + @Deployment(resources = { + "processes/failing-process.bpmn", + "processes/call-activity.bpmn", + "processes/nested-call-activity.bpmn" + }) + public void testQueryByProcessDefinitionIds() { + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("NestedCallActivity"); + + executeAvailableJobs(); + + String processDefinition2 = repositoryService.createProcessDefinitionQuery().processDefinitionKey("CallActivity").singleResult().getId(); + + String[] processDefinitionIds = { processInstance.getProcessDefinitionId(), processDefinition2 }; + + IncidentQueryDto queryParameter = new IncidentQueryDto(); + queryParameter.setProcessDefinitionIdIn(processDefinitionIds); + + List result = resource.queryIncidents(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + } + + @Test + @Deployment(resources = { + "processes/failing-process.bpmn", + "processes/call-activity.bpmn", + "processes/nested-call-activity.bpmn" + }) + public void testQuerySorting() { + runtimeService.startProcessInstanceByKey("NestedCallActivity"); + + executeAvailableJobs(); + + // asc + verifySorting("incidentMessage", "asc", 3); + verifySorting("incidentTimestamp", "asc", 3); + verifySorting("incidentType", "asc", 3); + verifySorting("activityId", "asc", 3); + verifySorting("causeIncidentProcessInstanceId", "asc", 3); + verifySorting("rootCauseIncidentProcessInstanceId", "asc", 3); + + // desc + verifySorting("incidentMessage", "desc", 3); + verifySorting("incidentTimestamp", "desc", 3); + verifySorting("incidentType", "desc", 3); + verifySorting("activityId", "desc", 3); + verifySorting("causeIncidentProcessInstanceId", "desc", 3); + verifySorting("rootCauseIncidentProcessInstanceId", "desc", 3); + } + + @Test + @Deployment(resources = "processes/simple-user-task-process.bpmn") + public void testQuerySortingByIncidentMessage() + { + // given + ProcessInstance instance = runtimeService.startProcessInstanceByKey("simpleUserTaskProcess"); + Incident incident1 = runtimeService.createIncident("foo", instance.getId(), null, "message1"); + Incident incident2 = runtimeService.createIncident("foo", instance.getId(), null, "message3"); + Incident incident3 = runtimeService.createIncident("foo", instance.getId(), null, "message2"); + + // when + List ascending = queryIncidents("incidentMessage", "asc"); + List descending = queryIncidents("incidentMessage", "desc"); + + // then + assertThat(ascending).extracting("id").containsExactly(incident1.getId(), incident3.getId(), incident2.getId()); + assertThat(descending).extracting("id").containsExactly(incident2.getId(), incident3.getId(), incident1.getId()); + } + + @Test + public void shouldReturnPaginatedResult() { + // given + processEngineConfiguration.setQueryMaxResultsLimit(10); + + identityService.setAuthenticatedUserId("foo"); + + try { + // when + resource.queryIncidents(new IncidentQueryDto(), 0, 10); + // then: no exception expected + } catch (BadUserRequestException e) { + // then + fail("No exception expected"); + } + } + + @Test + public void shouldReturnUnboundedResult_NotAuthenticated() { + // given + processEngineConfiguration.setQueryMaxResultsLimit(10); + + try { + // when + resource.queryIncidents(new IncidentQueryDto(), null, null); + // then: no exception expected + } catch (BadUserRequestException e) { + // then + fail("No exception expected"); + } + } + + @Test + public void shouldReturnUnboundedResult_NoLimitConfigured() { + // given + identityService.setAuthenticatedUserId("foo"); + + try { + // when + resource.queryIncidents(new IncidentQueryDto(), null, null); + // then: no exception expected + } catch (BadUserRequestException e) { + // then + fail("No exception expected"); + } + } + + @Test + public void shouldThrowExceptionWhenMaxResultsLimitExceeded() { + // given + processEngineConfiguration.setQueryMaxResultsLimit(10); + + identityService.setAuthenticatedUserId("foo"); + + try { + // when + resource.queryIncidents(new IncidentQueryDto(), 0, 11); + fail("Exception expected!"); + } catch (BadUserRequestException e) { + // then + assertThat(e).hasMessage("Max results limit of 10 exceeded!"); + } + } + + @Test + public void shouldThrowExceptionWhenQueryUnbounded() { + // given + processEngineConfiguration.setQueryMaxResultsLimit(10); + + identityService.setAuthenticatedUserId("foo"); + + try { + // when + resource.queryIncidents(new IncidentQueryDto(), null, null); + fail("Exception expected!"); + } catch (BadUserRequestException e) { + // then + assertThat(e).hasMessage("An unbound number of results is forbidden!"); + } + } + + protected List queryIncidents(String sorting, String order) + { + IncidentQueryDto queryParameter = new IncidentQueryDto(); + queryParameter.setSortBy(sorting); + queryParameter.setSortOrder(order); + + return resource.queryIncidents(queryParameter, null, null); + } + + protected void verifySorting(String sortBy, String sortOrder, int expectedResult) { + List result = queryIncidents(sortBy, sortOrder); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(expectedResult); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/PluginQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/PluginQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d53c54ba1282ca82c3c961a69a88c4a8b0e2dd6e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/PluginQueryTest.java @@ -0,0 +1,41 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.camunda.bpm.cockpit.db.QueryParameters; +import org.camunda.bpm.cockpit.plugin.test.AbstractCockpitPluginTest; +import org.camunda.bpm.engine.runtime.Execution; +import org.junit.Test; + +/** + * + * @author nico.rehwaldt + */ +public class PluginQueryTest extends AbstractCockpitPluginTest { + + @Test + public void testCustomQuery() { + + List result = getQueryService().executeQuery("cockpit.base.selectProcessDefinitionWithFailedJobs", new QueryParameters()); + + assertThat(result).hasSize(0); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/ProcessDefinitionResourceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/ProcessDefinitionResourceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..fa3e1c211aab706bf0110bc0eb51bacbbb6d0291 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/ProcessDefinitionResourceTest.java @@ -0,0 +1,683 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base; + +import static junit.framework.TestCase.fail; +import static org.camunda.bpm.engine.rest.dto.ConditionQueryParameterDto.EQUALS_OPERATOR_NAME; +import static org.camunda.bpm.engine.rest.dto.ConditionQueryParameterDto.LIKE_OPERATOR_NAME; +import static org.camunda.bpm.engine.rest.dto.ConditionQueryParameterDto.NOT_EQUALS_OPERATOR_NAME; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.ProcessDefinitionDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.query.ProcessDefinitionQueryDto; +import org.camunda.bpm.cockpit.impl.plugin.base.sub.resources.ProcessDefinitionResource; +import org.camunda.bpm.cockpit.plugin.test.AbstractCockpitPluginTest; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.db.sql.DbSqlSessionFactory; +import org.camunda.bpm.engine.impl.test.RequiredDatabase; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.rest.dto.VariableQueryParameterDto; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.test.Deployment; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ProcessDefinitionResourceTest extends AbstractCockpitPluginTest { + + private ProcessEngine processEngine; + protected ProcessEngineConfigurationImpl processEngineConfiguration; + private RuntimeService runtimeService; + private RepositoryService repositoryService; + private ProcessDefinitionResource resource; + protected IdentityService identityService; + + @Before + public void setUp() throws Exception { + super.before(); + + processEngine = getProcessEngine(); + processEngineConfiguration = (ProcessEngineConfigurationImpl) processEngine + .getProcessEngineConfiguration(); + + runtimeService = processEngine.getRuntimeService(); + repositoryService = processEngine.getRepositoryService(); + identityService = processEngine.getIdentityService(); + } + + @After + public void clearAuthentication() { + identityService.clearAuthentication(); + } + + @After + public void resetQueryMaxResultsLimit() { + processEngineConfiguration.setQueryMaxResultsLimit(Integer.MAX_VALUE); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn", + "processes/calling-user-task-process.bpmn" + }) + public void testCalledProcessDefinitionByParentProcessDefinitionId() { + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("CallingUserTaskProcess"); + + resource = new ProcessDefinitionResource(getProcessEngine().getName(), processInstance.getProcessDefinitionId()); + + ProcessDefinition userTaskProcess = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("userTaskProcess") + .singleResult(); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + + List result = resource.queryCalledProcessDefinitions(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessDefinitionDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(userTaskProcess.getId()); + assertThat(dto.getKey()).isEqualTo(userTaskProcess.getKey()); + assertThat(dto.getName()).isEqualTo(userTaskProcess.getName()); + assertThat(dto.getVersion()).isEqualTo(userTaskProcess.getVersion()); + assertThat(dto.getCalledFromActivityIds()).hasSize(1); + + String calledFrom = dto.getCalledFromActivityIds().get(0); + + assertThat(calledFrom).isEqualTo("CallActivity_1"); + + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn", + "processes/two-parallel-call-activities-calling-same-process.bpmn" + }) + public void testCalledProcessDefinitionByParentProcessDefinitionIdWithTwoActivityCallingSameProcess() { + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("TwoParallelCallActivitiesCallingSameProcess"); + + resource = new ProcessDefinitionResource(getProcessEngine().getName(), processInstance.getProcessDefinitionId()); + + ProcessDefinition userTaskProcess = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("userTaskProcess") + .singleResult(); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + + List result = resource.queryCalledProcessDefinitions(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessDefinitionDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(userTaskProcess.getId()); + assertThat(dto.getKey()).isEqualTo(userTaskProcess.getKey()); + assertThat(dto.getName()).isEqualTo(userTaskProcess.getName()); + assertThat(dto.getVersion()).isEqualTo(userTaskProcess.getVersion()); + assertThat(dto.getCalledFromActivityIds()).hasSize(2); + + for (String activityId : dto.getCalledFromActivityIds()) { + if (activityId.equals("firstCallActivity")) { + assertThat(activityId).isEqualTo("firstCallActivity"); + } else if (activityId.equals("secondCallActivity")) { + assertThat(activityId).isEqualTo("secondCallActivity"); + } else { + Assert.fail("Unexpected activity id:" + activityId); + } + } + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn", + "processes/two-parallel-call-activities-calling-same-process.bpmn", + "processes/calling-user-task-process.bpmn" + }) + public void testCalledProcessDefinitionByCallingSameProcessFromDifferentProcessDefinitions() { + ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("TwoParallelCallActivitiesCallingSameProcess"); + ProcessDefinitionResource resource1 = new ProcessDefinitionResource(getProcessEngine().getName(), processInstance1.getProcessDefinitionId()); + + ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("CallingUserTaskProcess"); + ProcessDefinitionResource resource2 = new ProcessDefinitionResource(getProcessEngine().getName(), processInstance2.getProcessDefinitionId()); + + ProcessDefinition userTaskProcess = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("userTaskProcess") + .singleResult(); + + ProcessDefinitionQueryDto queryParameter1 = new ProcessDefinitionQueryDto(); + + List result1 = resource1.queryCalledProcessDefinitions(queryParameter1); + assertThat(result1).isNotEmpty(); + assertThat(result1).hasSize(1); + + ProcessDefinitionDto dto1 = result1.get(0); + + assertThat(dto1.getId()).isEqualTo(userTaskProcess.getId()); + assertThat(dto1.getKey()).isEqualTo(userTaskProcess.getKey()); + assertThat(dto1.getName()).isEqualTo(userTaskProcess.getName()); + assertThat(dto1.getVersion()).isEqualTo(userTaskProcess.getVersion()); + assertThat(dto1.getCalledFromActivityIds()).hasSize(2); + + for (String activityId : dto1.getCalledFromActivityIds()) { + if (activityId.equals("firstCallActivity")) { + assertThat(activityId).isEqualTo("firstCallActivity"); + } else if (activityId.equals("secondCallActivity")) { + assertThat(activityId).isEqualTo("secondCallActivity"); + } else { + Assert.fail("Unexpected activity id:" + activityId); + } + } + + ProcessDefinitionQueryDto queryParameter2 = new ProcessDefinitionQueryDto(); + + List result2 = resource2.queryCalledProcessDefinitions(queryParameter2); + assertThat(result2).isNotEmpty(); + assertThat(result2).hasSize(1); + + ProcessDefinitionDto dto2 = result2.get(0); + + assertThat(dto2.getId()).isEqualTo(userTaskProcess.getId()); + assertThat(dto2.getKey()).isEqualTo(userTaskProcess.getKey()); + assertThat(dto2.getName()).isEqualTo(userTaskProcess.getName()); + assertThat(dto2.getVersion()).isEqualTo(userTaskProcess.getVersion()); + assertThat(dto2.getCalledFromActivityIds()).hasSize(1); + + String calledFrom = dto2.getCalledFromActivityIds().get(0); + + assertThat(calledFrom).isEqualTo("CallActivity_1"); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn", + "processes/two-parallel-call-activities-calling-different-process.bpmn" + }) + public void testCalledProcessDefinitionByCallingDifferentProcessFromSameProcessDefinitions() { + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("TwoParallelCallActivitiesCallingDifferentProcess"); + + resource = new ProcessDefinitionResource(getProcessEngine().getName(), processInstance.getProcessDefinitionId()); + + ProcessDefinition userTaskProcess = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("userTaskProcess") + .singleResult(); + + ProcessDefinition anotherUserTaskProcess = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("anotherUserTaskProcess") + .singleResult(); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + + List result = resource.queryCalledProcessDefinitions(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + ProcessDefinition compareWith = null; + for (ProcessDefinitionDto dto : result) { + String id = dto.getId(); + if (id.equals(userTaskProcess.getId())) { + compareWith = userTaskProcess; + assertThat(dto.getCalledFromActivityIds()).hasSize(1); + + String calledFrom = dto.getCalledFromActivityIds().get(0); + + assertThat(calledFrom).isEqualTo("firstCallActivity"); + + } else if (id.equals(anotherUserTaskProcess.getId())) { + compareWith = anotherUserTaskProcess; + assertThat(dto.getCalledFromActivityIds()).hasSize(1); + + String calledFrom = dto.getCalledFromActivityIds().get(0); + + assertThat(calledFrom).isEqualTo("secondCallActivity"); + + } else { + Assert.fail("Unexpected process definition: " + id); + } + + assertThat(dto.getId()).isEqualTo(compareWith.getId()); + assertThat(dto.getKey()).isEqualTo(compareWith.getKey()); + assertThat(dto.getName()).isEqualTo(compareWith.getName()); + assertThat(dto.getVersion()).isEqualTo(compareWith.getVersion()); + } + + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn", + "processes/dynamic-call-activity.bpmn" + }) + public void testCalledProcessDefinitionByCallingDifferentProcessFromSameCallActivity() { + Map vars1 = new HashMap(); + vars1.put("callProcess", "userTaskProcess"); + runtimeService.startProcessInstanceByKey("DynamicCallActivity", vars1); + + Map vars2 = new HashMap(); + vars2.put("callProcess", "anotherUserTaskProcess"); + runtimeService.startProcessInstanceByKey("DynamicCallActivity", vars2); + + ProcessDefinition dynamicCallActivity = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("DynamicCallActivity") + .singleResult(); + + resource = new ProcessDefinitionResource(getProcessEngine().getName(), dynamicCallActivity.getId()); + + ProcessDefinition userTaskProcess = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("userTaskProcess") + .singleResult(); + + ProcessDefinition anotherUserTaskProcess = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("anotherUserTaskProcess") + .singleResult(); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + + List result = resource.queryCalledProcessDefinitions(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + ProcessDefinition compareWith = null; + for (ProcessDefinitionDto dto : result) { + String id = dto.getId(); + if (id.equals(userTaskProcess.getId())) { + compareWith = userTaskProcess; + } else if (id.equals(anotherUserTaskProcess.getId())) { + compareWith = anotherUserTaskProcess; + } else { + Assert.fail("Unexpected process definition: " + id); + } + + assertThat(dto.getId()).isEqualTo(compareWith.getId()); + assertThat(dto.getKey()).isEqualTo(compareWith.getKey()); + assertThat(dto.getName()).isEqualTo(compareWith.getName()); + assertThat(dto.getVersion()).isEqualTo(compareWith.getVersion()); + assertThat(dto.getCalledFromActivityIds()).hasSize(1); + + String calledFrom = dto.getCalledFromActivityIds().get(0); + + assertThat(calledFrom).isEqualTo("dynamicCallActivity"); + } + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn", + "processes/calling-user-task-process.bpmn", + "processes/nested-calling-user-task-process.bpmn" + }) + public void testCalledProcessDefinitionQueryBySuperProcessDefinitionId() { + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("NestedCallingUserTaskProcess"); + + ProcessDefinition callingUserTaskProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("CallingUserTaskProcess") + .singleResult(); + + ProcessDefinition userTaskProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("userTaskProcess") + .singleResult(); + + resource = new ProcessDefinitionResource(getProcessEngine().getName(), callingUserTaskProcess.getId()); + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + queryParameter.setSuperProcessDefinitionId(processInstance.getProcessDefinitionId()); + + List result = resource.queryCalledProcessDefinitions(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessDefinitionDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(userTaskProcess.getId()); + assertThat(dto.getKey()).isEqualTo(userTaskProcess.getKey()); + assertThat(dto.getName()).isEqualTo(userTaskProcess.getName()); + assertThat(dto.getVersion()).isEqualTo(userTaskProcess.getVersion()); + assertThat(dto.getCalledFromActivityIds()).hasSize(1); + + String calledFrom = dto.getCalledFromActivityIds().get(0); + + assertThat(calledFrom).isEqualTo("CallActivity_1"); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn", + "processes/two-parallel-call-activities-calling-different-process.bpmn" + }) + public void testCalledProcessDefinitionQueryByActivityId() { + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("TwoParallelCallActivitiesCallingDifferentProcess"); + resource = new ProcessDefinitionResource(getProcessEngine().getName(), processInstance.getProcessDefinitionId()); + + ProcessDefinition userTaskProcess = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("userTaskProcess") + .singleResult(); + + ProcessDefinition anotherUserTaskProcess = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("anotherUserTaskProcess") + .singleResult(); + + ProcessDefinitionQueryDto queryParameter1 = new ProcessDefinitionQueryDto(); + String[] activityIds1 = {"firstCallActivity"}; + queryParameter1.setActivityIdIn(activityIds1); + + List result1 = resource.queryCalledProcessDefinitions(queryParameter1); + assertThat(result1).isNotEmpty(); + assertThat(result1).hasSize(1); + + ProcessDefinitionDto dto1 = result1.get(0); + + assertThat(dto1.getId()).isEqualTo(userTaskProcess.getId()); + assertThat(dto1.getKey()).isEqualTo(userTaskProcess.getKey()); + assertThat(dto1.getName()).isEqualTo(userTaskProcess.getName()); + assertThat(dto1.getVersion()).isEqualTo(userTaskProcess.getVersion()); + assertThat(dto1.getCalledFromActivityIds()).hasSize(1); + + String calledFrom1 = dto1.getCalledFromActivityIds().get(0); + + assertThat(calledFrom1).isEqualTo("firstCallActivity"); + + ProcessDefinitionQueryDto queryParameter2 = new ProcessDefinitionQueryDto(); + String[] activityIds2 = {"secondCallActivity"}; + queryParameter2.setActivityIdIn(activityIds2); + + List result2 = resource.queryCalledProcessDefinitions(queryParameter2); + assertThat(result2).isNotEmpty(); + assertThat(result2).hasSize(1); + + ProcessDefinitionDto dto2 = result2.get(0); + + assertThat(dto2.getId()).isEqualTo(anotherUserTaskProcess.getId()); + assertThat(dto2.getKey()).isEqualTo(anotherUserTaskProcess.getKey()); + assertThat(dto2.getName()).isEqualTo(anotherUserTaskProcess.getName()); + assertThat(dto2.getVersion()).isEqualTo(anotherUserTaskProcess.getVersion()); + assertThat(dto2.getCalledFromActivityIds()).hasSize(1); + + String calledFrom2 = dto2.getCalledFromActivityIds().get(0); + + assertThat(calledFrom2).isEqualTo("secondCallActivity"); + + ProcessDefinitionQueryDto queryParameter3 = new ProcessDefinitionQueryDto(); + String[] activityIds3 = {"firstCallActivity", "secondCallActivity"}; + queryParameter3.setActivityIdIn(activityIds3); + + List result3 = resource.queryCalledProcessDefinitions(queryParameter3); + assertThat(result3).isNotEmpty(); + assertThat(result3).hasSize(2); + + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn", + "processes/two-parallel-call-activities-calling-different-process.bpmn" + }) + public void testCalledProcessDefinitionQueryByBusinessKey() { + runtimeService.startProcessInstanceByKey("TwoParallelCallActivitiesCallingDifferentProcess", "aBusinessKey"); + runtimeService.startProcessInstanceByKey("TwoParallelCallActivitiesCallingDifferentProcess", "anotherBusinessKey"); + + ProcessDefinition parallelProcess = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("TwoParallelCallActivitiesCallingDifferentProcess") + .singleResult(); + + resource = new ProcessDefinitionResource(getProcessEngine().getName(), parallelProcess.getId()); + + ProcessDefinitionQueryDto queryParameter1 = new ProcessDefinitionQueryDto(); + queryParameter1.setBusinessKey("aBusinessKey"); + + List result1 = resource.queryCalledProcessDefinitions(queryParameter1); + assertThat(result1).isNotEmpty(); + assertThat(result1).hasSize(2); + + ProcessDefinitionQueryDto queryParameter2 = new ProcessDefinitionQueryDto(); + queryParameter2.setBusinessKey("anotherBusinessKey"); + + List result2 = resource.queryCalledProcessDefinitions(queryParameter2); + assertThat(result2).isNotEmpty(); + assertThat(result2).hasSize(2); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn", + "processes/two-parallel-call-activities-calling-different-process.bpmn" + }) + public void testCalledProcessDefinitionQueryByInvalidBusinessKey() { + runtimeService.startProcessInstanceByKey("TwoParallelCallActivitiesCallingDifferentProcess", "aBusinessKey"); + + ProcessDefinition parallelProcess = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("TwoParallelCallActivitiesCallingDifferentProcess") + .singleResult(); + + resource = new ProcessDefinitionResource(getProcessEngine().getName(), parallelProcess.getId()); + + ProcessDefinitionQueryDto queryParameter1 = new ProcessDefinitionQueryDto(); + queryParameter1.setBusinessKey("anInvalidBusinessKey"); + + List result1 = resource.queryCalledProcessDefinitions(queryParameter1); + assertThat(result1).isEmpty(); + assertThat(result1).hasSize(0); + + } + + @Test + @Deployment(resources = { + "processes/variables-process-with-call-activity.bpmn", + "processes/user-task-process.bpmn" + }) + public void testQueryWithBooleanVariable() { + // given + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("variableProcessWithCallActivity"); + resource = new ProcessDefinitionResource(getProcessEngine().getName(), processInstance.getProcessDefinitionId()); + + // when + VariableQueryParameterDto variable = createVariableParameter("varboolean", EQUALS_OPERATOR_NAME, false); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + queryParameter.setVariables(Arrays.asList(variable)); + + List results = resource.queryCalledProcessDefinitions(queryParameter); + + // then + assertThat(results).hasSize(0); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn", + "processes/dynamic-call-activity.bpmn" + }) + public void testQueryWithVariable() { + // given + Map vars1 = new HashMap(); + vars1.put("callProcess", "userTaskProcess"); + vars1.put("aVariableName", "test_123"); + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("DynamicCallActivity", vars1); + + Map vars2 = new HashMap(); + vars2.put("callProcess", "anotherUserTaskProcess"); + vars1.put("aVariableName", "test_456"); + runtimeService.startProcessInstanceByKey("DynamicCallActivity", vars2); + + resource = new ProcessDefinitionResource(getProcessEngine().getName(), processInstance.getProcessDefinitionId()); + + ProcessDefinition userTaskProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("userTaskProcess") + .singleResult(); + + // when + VariableQueryParameterDto variable = createVariableParameter("aVariableName", LIKE_OPERATOR_NAME, "test\\_1%"); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + queryParameter.setVariables(Arrays.asList(variable)); + + // then + List results = resource.queryCalledProcessDefinitions(queryParameter); + assertThat(results).isNotEmpty(); + assertThat(results).hasSize(1); + + ProcessDefinitionDto dto = results.get(0); + + assertThat(dto.getId()).isEqualTo(userTaskProcess.getId()); + assertThat(dto.getKey()).isEqualTo(userTaskProcess.getKey()); + assertThat(dto.getName()).isEqualTo(userTaskProcess.getName()); + } + + @Test + @Deployment(resources = { + "processes/variables-process-with-call-activity.bpmn", + "processes/user-task-process.bpmn" + }) + public void testQueryWithStringVariable() { + // given + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("variableProcessWithCallActivity"); + resource = new ProcessDefinitionResource(getProcessEngine().getName(), processInstance.getProcessDefinitionId()); + + // when + VariableQueryParameterDto variable = createVariableParameter("varstring", LIKE_OPERATOR_NAME, "B%"); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + queryParameter.setVariables(Arrays.asList(variable)); + + List results = resource.queryCalledProcessDefinitions(queryParameter); + + // then + assertThat(results).hasSize(0); + } + + @Test + @Deployment(resources = { + "processes/variables-process-with-call-activity.bpmn", + "processes/user-task-process.bpmn" + }) + public void testQueryWithFloatVariable() { + // given + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("variableProcessWithCallActivity"); + resource = new ProcessDefinitionResource(getProcessEngine().getName(), processInstance.getProcessDefinitionId()); + + // when + VariableQueryParameterDto variable = createVariableParameter("varfloat", EQUALS_OPERATOR_NAME, 0.0); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + queryParameter.setVariables(Arrays.asList(variable)); + + List results = resource.queryCalledProcessDefinitions(queryParameter); + + // then + assertThat(results).hasSize(0); + } + + @Test + @Deployment(resources = { + "processes/variables-process-with-call-activity.bpmn", + "processes/user-task-process.bpmn" + }) + public void testQueryWithIntegerVariable() { + // given + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("variableProcessWithCallActivity"); + resource = new ProcessDefinitionResource(getProcessEngine().getName(), processInstance.getProcessDefinitionId()); + + // when + VariableQueryParameterDto variable = createVariableParameter("varinteger", NOT_EQUALS_OPERATOR_NAME, 12); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + queryParameter.setVariables(Arrays.asList(variable)); + + List results = resource.queryCalledProcessDefinitions(queryParameter); + + // then + assertThat(results).hasSize(0); + } + + @Test + @Deployment(resources = { + "processes/variables-process-with-call-activity.bpmn", + "processes/user-task-process.bpmn" + }) + @RequiredDatabase(excludes = {DbSqlSessionFactory.MYSQL}) + public void testQueryWithComplexVariableFilter() { + // given + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("variableProcessWithCallActivity"); + resource = new ProcessDefinitionResource(getProcessEngine().getName(), processInstance.getProcessDefinitionId()); + + // when + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + queryParameter.setVariables(Arrays.asList( + createVariableParameter("varinteger", VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME, 11), + createVariableParameter("varinteger", VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME, 12), + createVariableParameter("varinteger", VariableQueryParameterDto.EQUALS_OPERATOR_NAME, 12), + createVariableParameter("varboolean", VariableQueryParameterDto.EQUALS_OPERATOR_NAME, true), + createVariableParameter("varboolean", VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME, false), + createVariableParameter("varstring", VariableQueryParameterDto.LIKE_OPERATOR_NAME, "F%"), + createVariableParameter("varstring", VariableQueryParameterDto.EQUALS_OPERATOR_NAME, "FOO"), + createVariableParameter("varstring", VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME, "BAR"), + createVariableParameter("varfloat", VariableQueryParameterDto.EQUALS_OPERATOR_NAME, 12.12), + createVariableParameter("varfloat", VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME, 13.0), + createVariableParameter("varfloat", VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME, 12.13))); + + // then + List results = resource.queryCalledProcessDefinitions(queryParameter); + assertThat(results).hasSize(1); + + } + + @Test + public void shouldNotThrowExceptionWhenQueryUnbounded() { + // given + resource = new ProcessDefinitionResource(getProcessEngine().getName(), "anId"); + + processEngineConfiguration.setQueryMaxResultsLimit(10); + + identityService.setAuthenticatedUserId("foo"); + + try { + // when + resource.queryCalledProcessDefinitions(new ProcessDefinitionQueryDto()); + // then: no exception thrown + } catch (BadUserRequestException e) { + fail("No exception expected"); + } + } + + private VariableQueryParameterDto createVariableParameter(String name, String operator, Object value) { + VariableQueryParameterDto variable = new VariableQueryParameterDto(); + variable.setName(name); + variable.setOperator(operator); + variable.setValue(value); + + return variable; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/ProcessDefinitionRestServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/ProcessDefinitionRestServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..cf51369f15b089f44a5c6d195a5260d38a96a3ec --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/ProcessDefinitionRestServiceTest.java @@ -0,0 +1,465 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.ProcessDefinitionStatisticsDto; +import org.camunda.bpm.cockpit.impl.plugin.resources.ProcessDefinitionRestService; +import org.camunda.bpm.cockpit.plugin.test.AbstractCockpitPluginTest; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.persistence.entity.SuspensionState; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.runtime.Execution; +import org.camunda.bpm.engine.runtime.Incident; +import org.camunda.bpm.model.bpmn.Bpmn; +import org.camunda.bpm.model.bpmn.BpmnModelInstance; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; +import java.util.Arrays; +import java.util.List; + +import static junit.framework.TestCase.fail; +import static org.assertj.core.api.Assertions.assertThat; + +public class ProcessDefinitionRestServiceTest extends AbstractCockpitPluginTest { + + private ProcessEngineConfigurationImpl processEngineConfiguration; + private RepositoryService repositoryService; + private RuntimeService runtimeService; + private ProcessDefinitionRestService resource; + private IdentityService identityService; + private UriInfo uriInfo; + private final MultivaluedMap queryParameters = new MultivaluedHashMap<>(); + + @Before + public void setUp() throws Exception { + super.before(); + + ProcessEngine processEngine = getProcessEngine(); + processEngineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration(); + repositoryService = processEngine.getRepositoryService(); + runtimeService = processEngine.getRuntimeService(); + identityService = processEngine.getIdentityService(); + + resource = new ProcessDefinitionRestService(processEngine.getName()); + + uriInfo = Mockito.mock(UriInfo.class); + Mockito.doReturn(queryParameters).when(uriInfo).getQueryParameters(); + } + + @After + public void tearDown() { + identityService.clearAuthentication(); + processEngineConfiguration.setQueryMaxResultsLimit(Integer.MAX_VALUE); + queryParameters.clear(); + repositoryService.createDeploymentQuery() + .list() + .forEach(deployment -> repositoryService.deleteDeployment(deployment.getId(), true)); + } + + private void deployProcesses(int count) { + deployProcesses(count, "ProcessDefinition", "Process Definition"); + } + + private void deployProcesses(int count, String key, String name) { + deployProcesses(count, key, name, 0, 0, "default"); + } + + private void deployProcesses(int count, String key, String name, int instances, int incidents, String tenantId) { + for (int i = 0; i < count; i++) { + String pdKey = key + (count > 1 ? "-" + i : ""); + BpmnModelInstance aProcessDefinition = Bpmn.createExecutableProcess(pdKey) + .name(name + (count > 1 ? " " + i : "")) + .startEvent() + .userTask("testQuerySuspensionStateTask") + .endEvent() + .done(); + ProcessDefinition processDefinition = repositoryService.createDeployment() + .addModelInstance(pdKey + ".bpmn", aProcessDefinition) + .name(pdKey) + .tenantId(tenantId) + .deployWithResult() + .getDeployedProcessDefinitions() + .get(0); + + if (instances > 0) { + for (int j = 0; j < instances; j++) { + runtimeService.startProcessInstanceById(processDefinition.getId()); + } + } + + if (incidents > 0) { + for (int k = 0; k < incidents; k++) { + Execution execution = runtimeService.createExecutionQuery() + .processDefinitionId(processDefinition.getId()) + .list() + .get(0); + runtimeService.createIncident("custom", execution.getId(), null); + } + } + } + } + + @Test + public void shouldThrowExceptionWhenMaxResultsLimitExceeded() { + // given + processEngineConfiguration.setQueryMaxResultsLimit(10); + identityService.setAuthenticatedUserId("foo"); + + try { + // when + resource.queryStatistics(uriInfo, 0, 11); + fail("Exception expected!"); + } catch (BadUserRequestException e) { + // then + assertThat(e).hasMessage("Max results limit of 10 exceeded!"); + } + } + + @Test + public void shouldThrowExceptionWhenQueryUnbounded() { + // given + processEngineConfiguration.setQueryMaxResultsLimit(10); + identityService.setAuthenticatedUserId("foo"); + + try { + // when + resource.queryStatistics(uriInfo, null, null); + fail("Exception expected!"); + } catch (BadUserRequestException e) { + // then + assertThat(e).hasMessage("An unbound number of results is forbidden!"); + } + } + + @Test + public void shouldReturnUnboundedResultWhenNotAuthenticated() { + // given + processEngineConfiguration.setQueryMaxResultsLimit(10); + + try { + // when + resource.queryStatistics(uriInfo, null, null); + // then: no exception expected + } catch (BadUserRequestException e) { + // then + fail("No exception expected"); + } + } + + protected void assertProcessDefinitionStatisticsDto(ProcessDefinitionStatisticsDto actual, + ProcessDefinition expected, + int expectedInstances, + int expectedIncidents) { + assertThat(actual.getId()).isEqualTo(expected.getId()); + assertThat(actual.getKey()).isEqualTo(expected.getKey()); + assertThat(actual.getName()).isEqualTo(expected.getName()); + assertThat(actual.getVersion()).isEqualTo(expected.getVersion()); + assertThat(actual.getTenantId()).isEqualTo(expected.getTenantId()); + assertThat(actual.getSuspensionState()).isEqualTo( + expected.isSuspended() ? SuspensionState.SUSPENDED.getStateCode() : SuspensionState.ACTIVE.getStateCode()); + assertThat(actual.getInstances()).isEqualTo(expectedInstances); + assertThat(actual.getIncidents()).isEqualTo(expectedIncidents); + } + + @Test + public void shouldAggregateResultsByKeyAndTenantId() { + // given + deployProcesses(1, "A", "Process A", 1, 3, "default"); + repositoryService.suspendProcessDefinitionByKey("A"); + deployProcesses(1, "A", "Process A v2", 1, 0, "default"); + deployProcesses(1, "A", "Process A v3", 2, 2, "default"); + ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("A") + .latestVersion() + .singleResult(); + + // when + List actual = resource.queryStatistics(uriInfo, null, null); + CountResultDto actualCount = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual).hasSize(1); + assertThat(actualCount.getCount()).isEqualTo(actual.size()); + assertProcessDefinitionStatisticsDto(actual.get(0), processDefinition, 4, 5); + } + + @Test + public void shouldNotAggregateIfTenantIdIsDifferent() { + // given + deployProcesses(1, "A", "Process A", 1, 3, "tenant1"); + repositoryService.suspendProcessDefinitionByKey("A"); + deployProcesses(1, "A", "Process A v2", 1, 0, "tenant1"); + deployProcesses(1, "A", "Process A v3", 2, 2, "tenant2"); + ProcessDefinition pdTenant1 = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("A") + .tenantIdIn("tenant1") + .latestVersion() + .singleResult(); + ProcessDefinition pdTenant2 = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey("A") + .tenantIdIn("tenant2") + .latestVersion() + .singleResult(); + queryParameters.add("sortBy", "tenantId"); + queryParameters.add("sortOrder", "asc"); + + // when + List actual = resource.queryStatistics(uriInfo, null, null); + CountResultDto actualCount = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual).hasSize(2); + assertThat(actualCount.getCount()).isEqualTo(actual.size()); + assertProcessDefinitionStatisticsDto(actual.get(0), pdTenant1, 2, 3); + assertProcessDefinitionStatisticsDto(actual.get(1), pdTenant2, 2, 2); + } + + protected void verifyPaginatedResult(int firstResult, int maxResults, int expectedResults) { + // when + List actual = resource.queryStatistics(uriInfo, firstResult, maxResults); + CountResultDto actualCount = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual).hasSize(expectedResults); + assertThat(actualCount.getCount()).isEqualTo(10); + for (int i = 0; i < expectedResults; i++) { + assertThat(actual.get(i).getKey()).isEqualTo("ProcessDefinition-" + (i + firstResult)); + assertThat(actual.get(i).getName()).isEqualTo("Process Definition " + (i + firstResult)); + } + } + + @Test + public void shouldReturnPaginatedResult() { + // given + deployProcesses(10); + queryParameters.add("sortBy", "key"); + queryParameters.add("sortOrder", "asc"); + + // verify pagination + verifyPaginatedResult(0, 2, 2); + verifyPaginatedResult(2, 2, 2); + verifyPaginatedResult(2, 10, 8); + verifyPaginatedResult(8, 10, 2); + } + + protected void verifyFilteredResult(String filterBy, String key, String name) { + // given + queryParameters.clear(); + queryParameters.add(filterBy, "key".equals(filterBy) ? key : name); + + // when + List actual = resource.queryStatistics(uriInfo, null, null); + CountResultDto actualCount = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual).hasSize(1); + assertThat(actualCount.getCount()).isEqualTo(actual.size()); + assertThat(actual.get(0).getKey()).isEqualTo(key); + assertThat(actual.get(0).getName()).isEqualTo(name); + } + + @Test + public void shouldFilterResultByKey() { + // given + deployProcesses(2); + deployProcesses(2, "Something", "Descriptive Name"); + + // verify filter by key + verifyFilteredResult("key", "ProcessDefinition-0", "Process Definition 0"); + verifyFilteredResult("key", "Something-1", "Descriptive Name 1"); + } + + @Test + public void shouldFilterResultByName() { + // given + deployProcesses(2); + deployProcesses(2, "Something", "Descriptive Name"); + + // verify filter by name + verifyFilteredResult("name", "ProcessDefinition-0", "Process Definition 0"); + verifyFilteredResult("name", "Something-1", "Descriptive Name 1"); + } + + private void verifyFilteredLikeResult(String filterBy, String filterValue, int expectedResults) { + // given + queryParameters.clear(); + queryParameters.add(filterBy, filterValue); + + // when + List actual = resource.queryStatistics(uriInfo, null, null); + CountResultDto actualCount = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual).hasSize(expectedResults); + assertThat(actualCount.getCount()).isEqualTo(actual.size()); + } + + @Test + public void shouldFilterResultByLike() { + // given + deployProcesses(2); + deployProcesses(2, "AwesomeProcess", "Descriptive Process Name"); + + // verify filter by keyLike + verifyFilteredLikeResult("keyLike", "%some%", 2); + verifyFilteredLikeResult("keyLike", "Proc%", 2); + verifyFilteredLikeResult("keyLike", "%-1", 2); + verifyFilteredLikeResult("keyLike", "%Process%", 4); + } + + @Test + public void shouldFilterResultByNameLike() { + // given + deployProcesses(2); + deployProcesses(2, "AwesomeProcess", "Descriptive Process Name"); + + // verify filter by nameLike + verifyFilteredLikeResult("nameLike", "%Definition%", 2); + verifyFilteredLikeResult("nameLike", "Descriptive%", 2); + verifyFilteredLikeResult("nameLike", "% 1", 2); + verifyFilteredLikeResult("nameLike", "%Process%", 4); + } + + private void verifyOrderedResult(String sortBy, String sortOrder, List expectedKeysOrder) { + // given + queryParameters.clear(); + queryParameters.add("sortBy", sortBy); + queryParameters.add("sortOrder", sortOrder); + + // when + List actual = resource.queryStatistics(uriInfo, null, null); + CountResultDto actualCount = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual).hasSize(4); + assertThat(actualCount.getCount()).isEqualTo(actual.size()); + for (int i = 0; i < expectedKeysOrder.size(); i++) { + String expectedKey = expectedKeysOrder.get(i); + assertThat(actual.get(i).getKey()).isEqualTo(expectedKey); + } + } + + @Test + public void shouldSortResult() { + // given + deployProcesses(1, "A", "Process A", 1, 3, "tenant2"); + deployProcesses(1, "B", "Process B", 3, 1, "tenant0"); + deployProcesses(1, "p1", "Process 1", 2, 2, "tenant3"); + deployProcesses(1, "p2", "Process 2", 0, 0, "tenant1"); + + // verify order by key + verifyOrderedResult("key", "asc", Arrays.asList("A", "B", "p1", "p2")); + verifyOrderedResult("key", "desc", Arrays.asList("p2", "p1", "B", "A")); + + // verify order by name + verifyOrderedResult("name", "asc", Arrays.asList("p1", "p2", "A", "B")); + verifyOrderedResult("name", "desc", Arrays.asList("B", "A", "p2", "p1")); + + // verify order by tenantId + verifyOrderedResult("tenantId", "asc", Arrays.asList("B", "p2", "A", "p1")); + verifyOrderedResult("tenantId", "desc", Arrays.asList("p1", "A", "p2", "B")); + + // verify order by instances + verifyOrderedResult("instances", "asc", Arrays.asList("p2", "A", "p1", "B")); + verifyOrderedResult("instances", "desc", Arrays.asList("B", "p1", "A", "p2")); + + // verify order by incidents + verifyOrderedResult("incidents", "asc", Arrays.asList("p2", "B", "p1", "A")); + verifyOrderedResult("incidents", "desc", Arrays.asList("A", "p1", "B", "p2")); + } + + @Test + public void shouldReturnCorrectStatistics() { + // given a process with two process instances + deployProcesses(1, "A", "Process A", 2, 0, "tenant1"); + + var processInstances = runtimeService.createExecutionQuery() + .processDefinitionKey("A") + .list(); + + assertThat(processInstances).hasSize(2); + + var processIncidents = runtimeService.createIncidentQuery() + .processDefinitionKeyIn("A") + .list(); + + assertIncidentSize(processIncidents, 0); + + var pi1 = processInstances.get(0); + var pi2 = processInstances.get(1); + + // and two different (failedJob, failedExternalTask) incidents occur for each process instance + + addIncidentToProcess(pi1, "failedJob"); + addIncidentToProcess(pi1, "failedExternalTask"); + + addIncidentToProcess(pi2, "failedJob"); + addIncidentToProcess(pi2, "failedExternalTask"); + + processIncidents = runtimeService.createIncidentQuery() + .processDefinitionKeyIn("A") + .list(); + + assertIncidentSize(processIncidents, 4); + + assertIncidentSize(processIncidents, "failedJob", 2); + assertIncidentSize(processIncidents, "failedExternalTask", 2); + + // when + var results = resource.queryStatistics(uriInfo, 0, 50); + + // then statistics should be correct + assertThat(results) + .withFailMessage("The result should contain one entry (process definition 'Process A')") + .hasSize(1); + + assertThat(results.get(0).getInstances()) + .withFailMessage("The number of process instances should be 2") + .isEqualTo(2); + + assertThat(results.get(0).getIncidents()) + .withFailMessage("The total number of incidents should be 4") + .isEqualTo(4); + } + + private void addIncidentToProcess(Execution processInstance, String incidentType) { + runtimeService.createIncident(incidentType, processInstance.getId(), "someConfig", "The message of failure"); + } + + private void assertIncidentSize(List incidents, int size) { + assertThat(incidents.size()).isEqualTo(size); + } + + private void assertIncidentSize(List incidents, String incidentType, int size) { + assertThat(incidents.stream() + .filter(incident -> incidentType.equals(incident.getIncidentType())) + .count()) + .isEqualTo(size); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/ProcessInstanceResourceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/ProcessInstanceResourceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..1d14f6c5477decedfd814e024701173710990674 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/ProcessInstanceResourceTest.java @@ -0,0 +1,279 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base; + +import static junit.framework.TestCase.fail; +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.SQLException; +import java.util.List; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.CalledProcessInstanceDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.IncidentStatisticsDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.ProcessInstanceDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.query.CalledProcessInstanceQueryDto; +import org.camunda.bpm.cockpit.impl.plugin.base.sub.resources.ProcessInstanceResource; +import org.camunda.bpm.cockpit.plugin.test.AbstractCockpitPluginTest; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.runtime.ActivityInstance; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.test.Deployment; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * @author roman.smirnov + */ +public class ProcessInstanceResourceTest extends AbstractCockpitPluginTest { + + private ProcessInstanceResource resource; + private ProcessEngine processEngine; + protected ProcessEngineConfigurationImpl processEngineConfiguration; + private RuntimeService runtimeService; + private RepositoryService repositoryService; + protected IdentityService identityService; + + @Before + public void setUp() throws Exception { + super.before(); + + processEngine = getProcessEngine(); + processEngineConfiguration = (ProcessEngineConfigurationImpl) getProcessEngine() + .getProcessEngineConfiguration(); + runtimeService = processEngine.getRuntimeService(); + repositoryService = processEngine.getRepositoryService(); + identityService = processEngine.getIdentityService(); + } + + @After + public void clearAuthentication() { + identityService.clearAuthentication(); + } + + @After + public void resetQueryMaxResultsLimit() { + processEngineConfiguration.setQueryMaxResultsLimit(Integer.MAX_VALUE); + } + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testGetCalledProcessInstancesByParentProcessInstanceId() { + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("TwoParallelCallActivitiesCallingDifferentProcess"); + + resource = new ProcessInstanceResource(getProcessEngine().getName(), processInstance.getId()); + + executeAvailableJobs(); + + ProcessDefinition userTaskProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("userTaskProcess") + .singleResult(); + + ProcessDefinition anotherUserTaskProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("anotherUserTaskProcess") + .singleResult(); + + CalledProcessInstanceQueryDto queryParameter = new CalledProcessInstanceQueryDto(); + + List result = resource.queryCalledProcessInstances(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + ProcessDefinition compareWith = null; + for (ProcessInstanceDto instance : result) { + CalledProcessInstanceDto dto = (CalledProcessInstanceDto) instance; + if (dto.getProcessDefinitionId().equals(userTaskProcess.getId())) { + compareWith = userTaskProcess; + assertThat(dto.getCallActivityId()).isEqualTo("firstCallActivity"); + } else if (dto.getProcessDefinitionId().equals(anotherUserTaskProcess.getId())) { + compareWith = anotherUserTaskProcess; + assertThat(dto.getCallActivityId()).isEqualTo("secondCallActivity"); + } else { + Assert.fail("Unexpected called process instance: " + dto.getId()); + } + + assertThat(dto.getCallActivityInstanceId()).isNotNull(); + + assertThat(dto.getProcessDefinitionId()).isEqualTo(compareWith.getId()); + assertThat(dto.getProcessDefinitionName()).isEqualTo(compareWith.getName()); + assertThat(dto.getProcessDefinitionKey()).isEqualTo(compareWith.getKey()); + } + } + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testGetCalledProcessInstancesByParentProcessInstanceIdContainsBusinessKey() { + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("TwoParallelCallActivitiesCallingDifferentProcess", "myBusinessKey"); + + resource = new ProcessInstanceResource(getProcessEngine().getName(), processInstance.getId()); + executeAvailableJobs(); + + CalledProcessInstanceQueryDto queryParameter = new CalledProcessInstanceQueryDto(); + + List result = resource.queryCalledProcessInstances(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + assertThat(result.get(0).getBusinessKey()).isEqualTo("firstCall:myBusinessKey"); + assertThat(result.get(1).getBusinessKey()).isEqualTo("secondCall:myBusinessKey"); + } + + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testGetCalledProcessInstancesByParentProcessInstanceIdAndActivityInstanceId() { + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("TwoParallelCallActivitiesCallingDifferentProcess"); + + resource = new ProcessInstanceResource(getProcessEngine().getName(), processInstance.getId()); + + ActivityInstance processInstanceActivityInstance = runtimeService.getActivityInstance(processInstance.getId()); + + String firstActivityInstanceId = null; + String secondActivityInstanceId = null; + + for (ActivityInstance child : processInstanceActivityInstance.getChildActivityInstances()) { + if (child.getActivityId().equals("firstCallActivity")) { + firstActivityInstanceId = child.getId(); + } else if (child.getActivityId().equals("secondCallActivity")) { + secondActivityInstanceId = child.getId(); + } else { + Assert.fail("Unexpected activity instance with activity id: " + child.getActivityId() + " and instance id: " + child.getId()); + } + } + + executeAvailableJobs(); + + CalledProcessInstanceQueryDto queryParameter1 = new CalledProcessInstanceQueryDto(); + + String[] activityInstanceIds1 = {firstActivityInstanceId}; + queryParameter1.setActivityInstanceIdIn(activityInstanceIds1); + + List result1 = resource.queryCalledProcessInstances(queryParameter1); + assertThat(result1).isNotEmpty(); + assertThat(result1).hasSize(1); + + CalledProcessInstanceQueryDto queryParameter2 = new CalledProcessInstanceQueryDto(); + String[] activityInstanceIds2 = {secondActivityInstanceId}; + queryParameter2.setActivityInstanceIdIn(activityInstanceIds2); + + List result2 = resource.queryCalledProcessInstances(queryParameter2); + assertThat(result2).isNotEmpty(); + assertThat(result2).hasSize(1); + + CalledProcessInstanceQueryDto queryParameter3 = new CalledProcessInstanceQueryDto(); + String[] activityInstanceIds3 = {firstActivityInstanceId, secondActivityInstanceId}; + queryParameter3.setActivityInstanceIdIn(activityInstanceIds3); + + List result3 = resource.queryCalledProcessInstances(queryParameter3); + assertThat(result3).isNotEmpty(); + assertThat(result3).hasSize(2); + } + + @Test + @Deployment(resources = { + "processes/call-activity.bpmn", + "processes/failing-process.bpmn" + }) + public void testCalledProcessIntancesIncidents() { + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("CallActivity"); + + resource = new ProcessInstanceResource(getProcessEngine().getName(), processInstance.getId()); + + runtimeService.getActivityInstance(processInstance.getId()); + + String processDefinition1 = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("CallActivity") + .singleResult() + .getId(); + + String processDefinition2 = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("FailingProcess") + .singleResult() + .getId(); + + executeAvailableJobs(); + + CalledProcessInstanceQueryDto queryParameter1 = new CalledProcessInstanceQueryDto(); + queryParameter1.setProcessDefinitionId(processDefinition1); + + List callActivityInstances = resource.queryCalledProcessInstances(queryParameter1); + assertThat(callActivityInstances).isNotEmpty(); + assertThat(callActivityInstances).hasSize(1); + + List incidents1 = callActivityInstances.get(0).getIncidents(); + assertThat(incidents1).isNotEmpty(); + assertThat(incidents1).hasSize(1); + + assertThat(incidents1.get(0).getIncidentCount()).isEqualTo(1); + assertThat(incidents1.get(0).getIncidentType()).isEqualTo("failedJob"); + + CalledProcessInstanceQueryDto queryParameter2 = new CalledProcessInstanceQueryDto(); + queryParameter2.setProcessDefinitionId(processDefinition2); + + List failingProcessInstance = resource.queryCalledProcessInstances(queryParameter2); + assertThat(failingProcessInstance).isNotEmpty(); + assertThat(failingProcessInstance).hasSize(1); + + List incidents2 = failingProcessInstance.get(0).getIncidents(); + assertThat(incidents2).isNotEmpty(); + assertThat(incidents2).hasSize(1); + + assertThat(incidents2.get(0).getIncidentCount()).isEqualTo(1); + assertThat(incidents2.get(0).getIncidentType()).isEqualTo("failedJob"); + } + + @Test + public void shouldNotThrowExceptionWhenQueryUnbounded() { + // given + resource = new ProcessInstanceResource(getProcessEngine().getName(), "anId"); + + processEngineConfiguration.setQueryMaxResultsLimit(10); + + identityService.setAuthenticatedUserId("foo"); + + try { + // when + resource.queryCalledProcessInstances(new CalledProcessInstanceQueryDto()); + // then: no exception thrown + } catch (BadUserRequestException e) { + fail("No exception expected"); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/ProcessInstanceRestServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/ProcessInstanceRestServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b01007c755a312bd1b12b33feac519976b6f5821 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/ProcessInstanceRestServiceTest.java @@ -0,0 +1,3513 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base; + +import static junit.framework.TestCase.fail; +import static org.camunda.bpm.engine.rest.dto.ConditionQueryParameterDto.EQUALS_OPERATOR_NAME; +import static org.camunda.bpm.engine.rest.dto.ConditionQueryParameterDto.GREATER_THAN_OPERATOR_NAME; +import static org.camunda.bpm.engine.rest.dto.ConditionQueryParameterDto.GREATER_THAN_OR_EQUALS_OPERATOR_NAME; +import static org.camunda.bpm.engine.rest.dto.ConditionQueryParameterDto.LESS_THAN_OPERATOR_NAME; +import static org.camunda.bpm.engine.rest.dto.ConditionQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME; +import static org.camunda.bpm.engine.rest.dto.ConditionQueryParameterDto.LIKE_OPERATOR_NAME; +import static org.camunda.bpm.engine.rest.dto.ConditionQueryParameterDto.NOT_EQUALS_OPERATOR_NAME; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.IncidentStatisticsDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.ProcessInstanceDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.query.ProcessInstanceQueryDto; +import org.camunda.bpm.cockpit.impl.plugin.resources.ProcessInstanceRestService; +import org.camunda.bpm.cockpit.plugin.test.AbstractCockpitPluginTest; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.db.sql.DbSqlSessionFactory; +import org.camunda.bpm.engine.impl.test.RequiredDatabase; +import org.camunda.bpm.engine.impl.util.ClockUtil; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.VariableQueryParameterDto; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.bpm.engine.test.RequiredHistoryLevel; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +/** + * @author roman.smirnov + * @author nico.rehwaldt + */ +@RequiredHistoryLevel(ProcessEngineConfiguration.HISTORY_AUDIT) +public class ProcessInstanceRestServiceTest extends AbstractCockpitPluginTest { + + private ProcessEngine processEngine; + protected ProcessEngineConfigurationImpl processEngineConfiguration; + private RuntimeService runtimeService; + private RepositoryService repositoryService; + protected IdentityService identityService; + + private ProcessInstanceRestService resource; + + @Before + public void setUp() throws Exception { + super.before(); + + processEngine = getProcessEngine(); + processEngineConfiguration = (ProcessEngineConfigurationImpl) getProcessEngine() + .getProcessEngineConfiguration(); + runtimeService = processEngine.getRuntimeService(); + repositoryService = processEngine.getRepositoryService(); + identityService = processEngine.getIdentityService(); + + resource = new ProcessInstanceRestService(processEngine.getName()); + } + + @After + public void clearAuthentication() { + identityService.clearAuthentication(); + } + + @After + public void resetQueryMaxResultsLimit() { + processEngineConfiguration.setQueryMaxResultsLimit(Integer.MAX_VALUE); + } + + private void startProcessInstances(String processDefinitionKey, int numOfInstances) { + for (int i = 0; i < numOfInstances; i++) { + ClockUtil.setCurrentTime(new Date(ClockUtil.getCurrentTime().getTime() + 1000)); + runtimeService.startProcessInstanceByKey(processDefinitionKey, "businessKey_" + i); + } + + executeAvailableJobs(); + } + + private void startProcessInstancesDelayed(String processDefinitionKey, int numOfInstances) { + for (int i = 0; i < numOfInstances; i++) { + ClockUtil.setCurrentTime(new Date(ClockUtil.getCurrentTime().getTime() + 3000)); + runtimeService.startProcessInstanceByKey(processDefinitionKey, "businessKey_" + i); + } + + executeAvailableJobs(); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQuery() { + startProcessInstances("userTaskProcess", 3); + + String processDefinitionId = repositoryService.createProcessDefinitionQuery().singleResult().getId(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setProcessDefinitionId(processDefinitionId); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(3); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryCount() { + startProcessInstances("userTaskProcess", 3); + + String processDefinitionId = repositoryService.createProcessDefinitionQuery().singleResult().getId(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setProcessDefinitionId(processDefinitionId); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + assertThat(result).isNotNull(); + assertThat(result.getCount()).isEqualTo(3); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryOrderByStartTime() { + startProcessInstancesDelayed("userTaskProcess", 3); + + String processDefinitionId = repositoryService.createProcessDefinitionQuery().singleResult().getId(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setProcessDefinitionId(processDefinitionId); + queryParameter.setSortBy("startTime"); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(3); + + for (int i=1; i < result.size(); i++) { + Date previousStartTime = result.get(i - 1).getStartTime(); + Date startTime = result.get(i).getStartTime(); + assertThat(startTime.after(previousStartTime)).isTrue(); + } + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryOrderByStartTimeAsc() { + startProcessInstancesDelayed("userTaskProcess", 3); + + String processDefinitionId = repositoryService.createProcessDefinitionQuery().singleResult().getId(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setProcessDefinitionId(processDefinitionId); + queryParameter.setSortBy("startTime"); + queryParameter.setSortOrder("asc"); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(3); + + for (int i=1; i < result.size(); i++) { + Date previousStartTime = result.get(i - 1).getStartTime(); + Date startTime = result.get(i).getStartTime(); + assertThat(startTime.after(previousStartTime)).isTrue(); + } + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryOrderByStartTimeDesc() { + startProcessInstancesDelayed("userTaskProcess", 3); + + String processDefinitionId = repositoryService.createProcessDefinitionQuery().singleResult().getId(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setProcessDefinitionId(processDefinitionId); + queryParameter.setSortBy("startTime"); + queryParameter.setSortOrder("desc"); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(3); + + for (int i=1; i < result.size(); i++) { + Date previousStartTime = result.get(i - 1).getStartTime(); + Date startTime = result.get(i).getStartTime(); + assertThat(startTime.before(previousStartTime)).isTrue(); + } + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryPagination() { + startProcessInstances("userTaskProcess", 5); + + String processDefinitionId = repositoryService.createProcessDefinitionQuery().singleResult().getId(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setProcessDefinitionId(processDefinitionId); + + List result = resource.queryProcessInstances(queryParameter, 0, 3); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(3); + + result = resource.queryProcessInstances(queryParameter, 2, 3); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(3); + + result = resource.queryProcessInstances(queryParameter, 3, 1); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryPaginationWithOrderByStartTimeDesc() { + startProcessInstancesDelayed("userTaskProcess", 8); + + String processDefinitionId = repositoryService.createProcessDefinitionQuery().singleResult().getId(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setProcessDefinitionId(processDefinitionId); + queryParameter.setSortBy("startTime"); + queryParameter.setSortOrder("desc"); + + List allResults = new ArrayList(); + + List result = resource.queryProcessInstances(queryParameter, 0, 3); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(3); + allResults.addAll(result); + + result = resource.queryProcessInstances(queryParameter, 3, 3); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(3); + allResults.addAll(result); + + result = resource.queryProcessInstances(queryParameter, 6, 3); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + allResults.addAll(result); + + for (int i=1; i < allResults.size(); i++) { + Date previousStartTime = allResults.get(i - 1).getStartTime(); + Date startTime = allResults.get(i).getStartTime(); + assertThat(startTime.before(previousStartTime)).isTrue(); + } + + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryPaginationWithOrderByStartTimeAsc() { + startProcessInstancesDelayed("userTaskProcess", 8); + + String processDefinitionId = repositoryService.createProcessDefinitionQuery().singleResult().getId(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setProcessDefinitionId(processDefinitionId); + queryParameter.setSortBy("startTime"); + queryParameter.setSortOrder("asc"); + + List allResults = new ArrayList(); + + List result = resource.queryProcessInstances(queryParameter, 0, 3); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(3); + allResults.addAll(result); + + result = resource.queryProcessInstances(queryParameter, 3, 3); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(3); + allResults.addAll(result); + + result = resource.queryProcessInstances(queryParameter, 6, 3); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + allResults.addAll(result); + + for (int i=1; i < allResults.size(); i++) { + Date previousStartTime = allResults.get(i - 1).getStartTime(); + Date startTime = allResults.get(i).getStartTime(); + assertThat(startTime.after(previousStartTime)).isTrue(); + } + + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryWithoutAnyIncident() { + startProcessInstances("userTaskProcess", 1); + + String processDefinitionId = repositoryService.createProcessDefinitionQuery().singleResult().getId(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setProcessDefinitionId(processDefinitionId); + + List result = resource.queryProcessInstances(queryParameter, null, null); + + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + List incidents = result.get(0).getIncidents(); + + assertThat(incidents).isEmpty(); + } + + @Test + @Deployment(resources = { + "processes/failing-process.bpmn" + }) + public void testQueryWithContainingIncidents() { + startProcessInstances("FailingProcess", 1); + + String processDefinitionId = repositoryService.createProcessDefinitionQuery().singleResult().getId(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setProcessDefinitionId(processDefinitionId); + + List result = resource.queryProcessInstances(queryParameter, null, null); + + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + List incidents = result.get(0).getIncidents(); + + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(1); + + IncidentStatisticsDto incident = incidents.get(0); + + assertThat(incident.getIncidentType()).isEqualTo("failedJob"); + assertThat(incident.getIncidentCount()).isEqualTo(1); + } + + @Test + @Deployment(resources = { + "processes/process-with-two-parallel-failing-services.bpmn" + }) + public void testQueryWithMoreThanOneIncident() { + startProcessInstances("processWithTwoParallelFailingServices", 1); + + String processDefinitionId = repositoryService.createProcessDefinitionQuery().singleResult().getId(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setProcessDefinitionId(processDefinitionId); + + List result = resource.queryProcessInstances(queryParameter, null, null); + + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + List incidents = result.get(0).getIncidents(); + + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(3); + + for (IncidentStatisticsDto incident : incidents) { + String incidentType = incident.getIncidentType(); + assertThat(incidentType).isNotNull(); + + if (incidentType.equals("failedJob")) { + assertThat(incident.getIncidentCount()).isEqualTo(2); + } else if (incidentType.equals("anIncident")) { + assertThat(incident.getIncidentCount()).isEqualTo(3); + } else if (incidentType.equals("anotherIncident")) { + assertThat(incident.getIncidentCount()).isEqualTo(5); + } else { + Assert.fail(incidentType + " not expected."); + } + + } + } + + @Test + @Deployment(resources = { + "processes/variables-process.bpmn" + }) + public void testQueryWithBooleanVariable() { + // given + startProcessInstances("variableProcess", 2); + + // when + VariableQueryParameterDto variable = createVariableParameter("varboolean", EQUALS_OPERATOR_NAME, false); + + ProcessInstanceQueryDto parameter = new ProcessInstanceQueryDto(); + parameter.setVariables(Arrays.asList(variable)); + + List results = resource.queryProcessInstances(parameter, 0, Integer.MAX_VALUE); + + // then + assertThat(results).hasSize(0); + } + + @Test + @Deployment(resources = { + "processes/variables-process.bpmn" + }) + public void testQueryWithStringVariable() { + // given + startProcessInstances("variableProcess", 2); + + // when + VariableQueryParameterDto variable = createVariableParameter("varstring", LIKE_OPERATOR_NAME, "B%"); + + ProcessInstanceQueryDto parameter = new ProcessInstanceQueryDto(); + parameter.setVariables(Arrays.asList(variable)); + + List results = resource.queryProcessInstances(parameter, 0, Integer.MAX_VALUE); + + // then + assertThat(results).hasSize(0); + } + + @Test + @Deployment(resources = { + "processes/variables-process.bpmn" + }) + public void testQueryWithFloatVariable() { + // given + startProcessInstances("variableProcess", 2); + + // when + VariableQueryParameterDto variable = createVariableParameter("varfloat", EQUALS_OPERATOR_NAME, 0.0); + + ProcessInstanceQueryDto parameter = new ProcessInstanceQueryDto(); + parameter.setVariables(Arrays.asList(variable)); + + List results = resource.queryProcessInstances(parameter, 0, Integer.MAX_VALUE); + + // then + assertThat(results).hasSize(0); + } + + @Test + @Deployment(resources = { + "processes/variables-process.bpmn" + }) + public void testQueryWithIntegerVariable() { + // given + startProcessInstances("variableProcess", 2); + + // when + VariableQueryParameterDto variable = createVariableParameter("varinteger", NOT_EQUALS_OPERATOR_NAME, 12); + + ProcessInstanceQueryDto parameter = new ProcessInstanceQueryDto(); + parameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(parameter, 0, Integer.MAX_VALUE); + + // then + assertThat(result).hasSize(0); + } + + @Test + @Deployment(resources = { + "processes/variables-process.bpmn" + }) + @RequiredDatabase(excludes = {DbSqlSessionFactory.MYSQL}) + public void testQueryWithComplexVariableFilter() { + // given + startProcessInstances("variableProcess", 2); + + // when + ProcessInstanceQueryDto parameter = new ProcessInstanceQueryDto(); + + parameter.setVariables(Arrays.asList( + createVariableParameter("varinteger", VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME, 11), + createVariableParameter("varinteger", VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME, 12), + createVariableParameter("varinteger", VariableQueryParameterDto.EQUALS_OPERATOR_NAME, 12), + createVariableParameter("varboolean", VariableQueryParameterDto.EQUALS_OPERATOR_NAME, true), + createVariableParameter("varboolean", VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME, false), + createVariableParameter("varstring", VariableQueryParameterDto.LIKE_OPERATOR_NAME, "F%"), + createVariableParameter("varstring", VariableQueryParameterDto.EQUALS_OPERATOR_NAME, "FOO"), + createVariableParameter("varstring", VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME, "BAR"), + createVariableParameter("varstring2", VariableQueryParameterDto.LIKE_OPERATOR_NAME, "F\\_%"), + createVariableParameter("varfloat", VariableQueryParameterDto.EQUALS_OPERATOR_NAME, 12.12), + createVariableParameter("varfloat", VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME, 13.0), + createVariableParameter("varfloat", VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME, 12.13))); + + List booleanProcessInstances = resource.queryProcessInstances(parameter, 0, Integer.MAX_VALUE); + assertThat(booleanProcessInstances).hasSize(2); + } + + @Test + @Deployment(resources = { + "processes/call-activity.bpmn", + "processes/nested-call-activity.bpmn", + "processes/failing-process.bpmn" + }) + public void testNestedIncidents() { + startProcessInstances("NestedCallActivity", 1); + + String nestedCallActivityId = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("NestedCallActivity") + .singleResult() + .getId(); + + String callActivityId = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("CallActivity") + .singleResult() + .getId(); + + String failingProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("FailingProcess") + .singleResult() + .getId(); + + ProcessInstanceQueryDto queryParameter1 = new ProcessInstanceQueryDto(); + queryParameter1.setProcessDefinitionId(nestedCallActivityId); + + List nestedCallActivityInstances = resource.queryProcessInstances(queryParameter1, null, null); + assertThat(nestedCallActivityInstances).isNotEmpty(); + assertThat(nestedCallActivityInstances).hasSize(1); + + List nestedCallActivityIncidents = nestedCallActivityInstances.get(0).getIncidents(); + assertThat(nestedCallActivityIncidents).isNotEmpty(); + assertThat(nestedCallActivityIncidents).hasSize(1); + + IncidentStatisticsDto nestedCallActivityIncident = nestedCallActivityIncidents.get(0); + assertThat(nestedCallActivityIncident.getIncidentType()).isEqualTo("failedJob"); + assertThat(nestedCallActivityIncident.getIncidentCount()).isEqualTo(1); + + ProcessInstanceQueryDto queryParameter2 = new ProcessInstanceQueryDto(); + queryParameter2.setProcessDefinitionId(callActivityId); + + List callActivityInstances = resource.queryProcessInstances(queryParameter2, null, null); + assertThat(callActivityInstances).isNotEmpty(); + assertThat(callActivityInstances).hasSize(1); + + List callActivityIncidents = callActivityInstances.get(0).getIncidents(); + assertThat(callActivityIncidents).isNotEmpty(); + assertThat(callActivityIncidents).hasSize(1); + + IncidentStatisticsDto callActivityIncident = callActivityIncidents.get(0); + assertThat(callActivityIncident.getIncidentType()).isEqualTo("failedJob"); + assertThat(callActivityIncident.getIncidentCount()).isEqualTo(1); + + ProcessInstanceQueryDto queryParameter3 = new ProcessInstanceQueryDto(); + queryParameter3.setProcessDefinitionId(failingProcess); + + List failingProcessInstances = resource.queryProcessInstances(queryParameter3, null, null); + assertThat(failingProcessInstances).isNotEmpty(); + assertThat(failingProcessInstances).hasSize(1); + + List failingProcessIncidents = failingProcessInstances.get(0).getIncidents(); + assertThat(failingProcessIncidents).isNotEmpty(); + assertThat(failingProcessIncidents).hasSize(1); + + IncidentStatisticsDto failingProcessIncident = failingProcessIncidents.get(0); + assertThat(failingProcessIncident.getIncidentType()).isEqualTo("failedJob"); + assertThat(failingProcessIncident.getIncidentCount()).isEqualTo(1); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryByBusinessKey() { + startProcessInstances("userTaskProcess", 3); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setBusinessKey("businessKey_2"); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryByBusinessKeyCount() { + startProcessInstances("userTaskProcess", 3); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setBusinessKey("businessKey_2"); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + assertThat(result).isNotNull(); + assertThat(result.getCount()).isEqualTo(1); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn", + "processes/failing-process.bpmn" + }) + public void testQueryByBusinessKeyWithMoreThanOneProcess() { + startProcessInstances("userTaskProcess", 3); + startProcessInstances("FailingProcess", 3); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setBusinessKey("businessKey_2"); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn", + "processes/failing-process.bpmn" + }) + public void testQueryByBusinessKeyWithMoreThanOneProcessCount() { + startProcessInstances("userTaskProcess", 3); + startProcessInstances("FailingProcess", 3); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setBusinessKey("businessKey_2"); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + assertThat(result).isNotNull(); + assertThat(result.getCount()).isEqualTo(2); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryByBusinessKeyAndProcessDefinition() { + startProcessInstances("userTaskProcess", 3); + + ProcessDefinition userTaskProcess = repositoryService.createProcessDefinitionQuery().singleResult(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setBusinessKey("businessKey_2"); + queryParameter.setProcessDefinitionId(userTaskProcess.getId()); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryByBusinessKeyAndProcessDefinitionCount() { + startProcessInstances("userTaskProcess", 3); + + ProcessDefinition userTaskProcess = repositoryService.createProcessDefinitionQuery().singleResult(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setBusinessKey("businessKey_2"); + queryParameter.setProcessDefinitionId(userTaskProcess.getId()); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + assertThat(result).isNotNull(); + assertThat(result.getCount()).isEqualTo(1); + } + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testQueryByActivityId() { + startProcessInstances("TwoParallelCallActivitiesCallingDifferentProcess", 2); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + String[] activityIds = {"firstCallActivity"}; + queryParameter.setActivityIdIn(activityIds); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + } + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testQueryByActivityIdCount() { + startProcessInstances("TwoParallelCallActivitiesCallingDifferentProcess", 2); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + String[] activityIds = {"firstCallActivity"}; + queryParameter.setActivityIdIn(activityIds); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + assertThat(result).isNotNull(); + assertThat(result.getCount()).isEqualTo(2); + } + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testQueryByActivityIds() { + startProcessInstances("TwoParallelCallActivitiesCallingDifferentProcess", 2); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + String[] activityIds = {"firstCallActivity", "secondCallActivity"}; + queryParameter.setActivityIdIn(activityIds); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + } + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testQueryByActivityIdsCount() { + startProcessInstances("TwoParallelCallActivitiesCallingDifferentProcess", 2); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + String[] activityIds = {"firstCallActivity", "secondCallActivity"}; + queryParameter.setActivityIdIn(activityIds); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + assertThat(result).isNotNull(); + assertThat(result.getCount()).isEqualTo(2); + } + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testQueryByActivityIdAndProcessDefinitionId() { + startProcessInstances("TwoParallelCallActivitiesCallingDifferentProcess", 2); + + ProcessDefinition processDef = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("TwoParallelCallActivitiesCallingDifferentProcess") + .singleResult(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setProcessDefinitionId(processDef.getId()); + String[] activityIds = {"firstCallActivity"}; + queryParameter.setActivityIdIn(activityIds); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + } + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testQueryByActivityIdAndProcessDefinitionIdCount() { + startProcessInstances("TwoParallelCallActivitiesCallingDifferentProcess", 2); + + ProcessDefinition processDef = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("TwoParallelCallActivitiesCallingDifferentProcess") + .singleResult(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setProcessDefinitionId(processDef.getId()); + String[] activityIds = {"firstCallActivity"}; + queryParameter.setActivityIdIn(activityIds); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + assertThat(result).isNotNull(); + assertThat(result.getCount()).isEqualTo(2); + } + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testQueryByParentProcessDefinitionId() { + startProcessInstances("TwoParallelCallActivitiesCallingDifferentProcess", 2); + + ProcessDefinition twoCallActivitiesProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("TwoParallelCallActivitiesCallingDifferentProcess") + .singleResult(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setParentProcessDefinitionId(twoCallActivitiesProcess.getId()); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(4); + } + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testQueryByParentProcessDefinitionIdCount() { + startProcessInstances("TwoParallelCallActivitiesCallingDifferentProcess", 2); + + ProcessDefinition twoCallActivitiesProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("TwoParallelCallActivitiesCallingDifferentProcess") + .singleResult(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setParentProcessDefinitionId(twoCallActivitiesProcess.getId()); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + assertThat(result).isNotNull(); + assertThat(result.getCount()).isEqualTo(4); + } + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testQueryByParentProcessDefinitionIdAndProcessDefinitionId() { + startProcessInstances("TwoParallelCallActivitiesCallingDifferentProcess", 2); + + ProcessDefinition twoCallActivitiesProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("TwoParallelCallActivitiesCallingDifferentProcess") + .singleResult(); + + ProcessDefinition userTaskProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("userTaskProcess") + .singleResult(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setParentProcessDefinitionId(twoCallActivitiesProcess.getId()); + + queryParameter.setProcessDefinitionId(userTaskProcess.getId()); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + } + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testQueryByParentProcessDefinitionIdAndProcessDefinitionIdCount() { + startProcessInstances("TwoParallelCallActivitiesCallingDifferentProcess", 2); + + ProcessDefinition twoCallActivitiesProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("TwoParallelCallActivitiesCallingDifferentProcess") + .singleResult(); + + ProcessDefinition userTaskProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("userTaskProcess") + .singleResult(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setParentProcessDefinitionId(twoCallActivitiesProcess.getId()); + queryParameter.setProcessDefinitionId(userTaskProcess.getId()); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + assertThat(result).isNotNull(); + assertThat(result.getCount()).isEqualTo(2); + } + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testQueryByParentProcessDefinitionIdAndProcessDefinitionIdAndActivityId() { + startProcessInstances("TwoParallelCallActivitiesCallingDifferentProcess", 2); + + ProcessDefinition twoCallActivitiesProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("TwoParallelCallActivitiesCallingDifferentProcess") + .singleResult(); + + ProcessDefinition userTaskProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("userTaskProcess") + .singleResult(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setParentProcessDefinitionId(twoCallActivitiesProcess.getId()); + queryParameter.setProcessDefinitionId(userTaskProcess.getId()); + String[] activityIds = {"theUserTask"}; + queryParameter.setActivityIdIn(activityIds); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + } + + @Test + @Deployment(resources = { + "processes/two-parallel-call-activities-calling-different-process.bpmn", + "processes/user-task-process.bpmn", + "processes/another-user-task-process.bpmn" + }) + public void testQueryByParentProcessDefinitionIdAndProcessDefinitionIdAndActivityIdCount() { + startProcessInstances("TwoParallelCallActivitiesCallingDifferentProcess", 2); + + ProcessDefinition twoCallActivitiesProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("TwoParallelCallActivitiesCallingDifferentProcess") + .singleResult(); + + ProcessDefinition userTaskProcess = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey("userTaskProcess") + .singleResult(); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setParentProcessDefinitionId(twoCallActivitiesProcess.getId()); + queryParameter.setProcessDefinitionId(userTaskProcess.getId()); + String[] activityIds = {"theUserTask"}; + queryParameter.setActivityIdIn(activityIds); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + assertThat(result).isNotNull(); + assertThat(result.getCount()).isEqualTo(2); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithIntegerVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithIntegerVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithIntegerVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithIntegerVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithIntegerVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithIntegerVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, 6); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithLongVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, (long) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithLongVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, (long) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithLongVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, (long) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithLongVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, (long) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithLongVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, (long) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithLongVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, (long) 6); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithShortVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, (short) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithShortVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, (short) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithShortVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, (short) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithShortVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, (short) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithShortVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, (short) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithShortVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, (short) 6); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithDoubleVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, 5.0); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithDoubleVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, 4.9); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithDoubleVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, 4.9); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithDoubleVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, 4.9); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithDoubleVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, 5.1); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterShortVariableWithDoubleVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", (short) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, 5.1); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithIntegerVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithIntegerVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithIntegerVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithIntegerVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithIntegerVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithIntegerVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, 6); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithLongVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, (long) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithLongVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, (long) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithLongVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, (long) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithLongVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, (long) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithLongVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, (long) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithLongVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, (long) 6); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithShortVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, (short) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithShortVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, (short) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithShortVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, (short) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithShortVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, (short) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithShortVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, (short) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithShortVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, (short) 6); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithDoubleVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, 5.0); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithDoubleVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, 4.9); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithDoubleVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, 4.9); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithDoubleVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, 4.9); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithDoubleVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, 5.1); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterIntegerVariableWithDoubleVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, 5.1); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithIntegerVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithIntegerVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithIntegerVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithIntegerVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithIntegerVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithIntegerVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, 6); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithLongVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, (long) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithLongVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, (long) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithLongVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, (long) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithLongVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, (long) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithLongVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, (long) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithLongVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, (long) 6); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithShortVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, (short) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithShortVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, (short) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithShortVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, (short) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithShortVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, (short) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithShortVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, (short) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithShortVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, (short) 6); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithDoubleVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, 5.0); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithDoubleVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, 4.9); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithDoubleVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, 4.9); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithDoubleVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, 4.9); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithDoubleVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, 5.1); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Ignore + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterLongVariableWithDoubleVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", (long) 5); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, 5.1); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithIntegerVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", 5.0); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithIntegerVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithIntegerVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", 5.0); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithIntegerVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithIntegerVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", 5.0); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithIntegerVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, 6); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithLongVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", 5.0); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, (long) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithLongVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, (long) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithLongVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, (long) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithLongVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, (long) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithLongVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", 5.0); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, (long) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithLongVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, (long) 6); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithShortVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", 5.0); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, (short) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithShortVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, (short) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithShortVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", (long) 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, (short) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithShortVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, (short) 4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithShortVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", 5.0); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, (short) 5); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithShortVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, (short) 6); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithDoubleVariable_Eq() { + Map vars = new HashMap(); + vars.put("var", 5.0); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", EQUALS_OPERATOR_NAME, 5.0); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithDoubleVariable_Neq() { + Map vars = new HashMap(); + vars.put("var", 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", NOT_EQUALS_OPERATOR_NAME, 4.9); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithDoubleVariable_Gteq() { + Map vars = new HashMap(); + vars.put("var", 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OR_EQUALS_OPERATOR_NAME, 5.3); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithDoubleVariable_Gt() { + Map vars = new HashMap(); + vars.put("var", 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", GREATER_THAN_OPERATOR_NAME, 4.9); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithDoubleVariable_Lteq() { + Map vars = new HashMap(); + vars.put("var", 5.1); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OR_EQUALS_OPERATOR_NAME, 5.1); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryAfterDoubleVariableWithDoubleVariable_Lt() { + Map vars = new HashMap(); + vars.put("var", 5.3); + + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userTaskProcess", vars); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + VariableQueryParameterDto variable = createVariableParameter("var", LESS_THAN_OPERATOR_NAME, 5.4); + queryParameter.setVariables(Arrays.asList(variable)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + ProcessInstanceDto dto = result.get(0); + + assertThat(dto.getId()).isEqualTo(processInstance.getId()); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryByStartedAfter() { + String date = "2014-01-01T13:13:00"; + Date currentDate = DateTimeUtil.parseDateTime(date).toDate(); + + ClockUtil.setCurrentTime(currentDate); + + startProcessInstances("userTaskProcess", 5); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setStartedAfter(currentDate); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(5); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryByStartedBefore() { + String date = "2014-01-01T13:13:00"; + Date currentDate = DateTimeUtil.parseDateTime(date).toDate(); + + ClockUtil.setCurrentTime(currentDate); + + startProcessInstances("userTaskProcess", 5); + + Calendar hourFromNow = Calendar.getInstance(); + hourFromNow.add(Calendar.HOUR_OF_DAY, 1); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setStartedBefore(hourFromNow.getTime()); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(5); + } + + @Test + @Deployment(resources = { + "processes/user-task-process.bpmn" + }) + public void testQueryByStartedBetween() { + String date = "2014-01-01T13:13:00"; + Date currentDate = DateTimeUtil.parseDateTime(date).toDate(); + + ClockUtil.setCurrentTime(currentDate); + + startProcessInstances("userTaskProcess", 5); + + Calendar hourFromNow = Calendar.getInstance(); + hourFromNow.add(Calendar.HOUR_OF_DAY, 1); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setStartedAfter(currentDate); + queryParameter.setStartedBefore(hourFromNow.getTime()); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(5); + } + + @Test + public void shouldReturnPaginatedResult() { + // given + processEngineConfiguration.setQueryMaxResultsLimit(10); + + identityService.setAuthenticatedUserId("foo"); + + try { + // when + resource.queryProcessInstances(new ProcessInstanceQueryDto(), 0, 10); + // then: no exception expected + } catch (BadUserRequestException e) { + // then + fail("No exception expected"); + } + } + + @Test + public void shouldReturnUnboundedResult_NotAuthenticated() { + // given + processEngineConfiguration.setQueryMaxResultsLimit(10); + + try { + // when + resource.queryProcessInstances(new ProcessInstanceQueryDto(), null, null); + // then: no exception expected + } catch (BadUserRequestException e) { + // then + fail("No exception expected"); + } + } + + @Test + public void shouldReturnUnboundedResult_NoLimitConfigured() { + // given + identityService.setAuthenticatedUserId("foo"); + + try { + // when + resource.queryProcessInstances(new ProcessInstanceQueryDto(), null, null); + // then: no exception expected + } catch (BadUserRequestException e) { + // then + fail("No exception expected"); + } + } + + @Test + public void shouldThrowExceptionWhenMaxResultsLimitExceeded() { + // given + processEngineConfiguration.setQueryMaxResultsLimit(10); + + identityService.setAuthenticatedUserId("foo"); + + try { + // when + resource.queryProcessInstances(new ProcessInstanceQueryDto(), 0, 11); + fail("Exception expected!"); + } catch (BadUserRequestException e) { + // then + assertThat(e).hasMessage("Max results limit of 10 exceeded!"); + } + } + + @Test + public void shouldThrowExceptionWhenQueryUnbounded() { + // given + processEngineConfiguration.setQueryMaxResultsLimit(10); + + identityService.setAuthenticatedUserId("foo"); + + try { + // when + resource.queryProcessInstances(new ProcessInstanceQueryDto(), null, null); + fail("Exception expected!"); + } catch (BadUserRequestException e) { + // then + assertThat(e).hasMessage("An unbound number of results is forbidden!"); + } + } + + @Test + @Deployment(resources = { + "processes/failing-process.bpmn", + "processes/user-task-process.bpmn" + }) + public void shouldFilterWithIncident() { + startProcessInstances("FailingProcess", 1); + startProcessInstances("userTaskProcess", 1); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setWithIncident(true); + + List result = resource.queryProcessInstances(queryParameter, null, null); + + assertThat(result).hasSize(1); + + List incidents = result.get(0).getIncidents(); + + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(1); + + IncidentStatisticsDto incident = incidents.get(0); + + assertThat(incident.getIncidentType()).isEqualTo("failedJob"); + assertThat(incident.getIncidentCount()).isEqualTo(1); + } + + @Test + @Deployment(resources = { + "processes/failing-process.bpmn", + "processes/user-task-process.bpmn" + }) + public void shouldFilterWithIncidentOnCount() { + startProcessInstances("FailingProcess", 1); + startProcessInstances("userTaskProcess", 1); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setWithIncident(true); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + + assertThat(result.getCount()).isEqualTo(1L); + } + + private VariableQueryParameterDto createVariableParameter(String name, String operator, Object value) { + VariableQueryParameterDto variable = new VariableQueryParameterDto(); + variable.setName(name); + variable.setOperator(operator); + variable.setValue(value); + + return variable; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/AuthorizationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/AuthorizationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..bbefcbbfbb84c39479dbe44bc3af3df91f89009d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/AuthorizationTest.java @@ -0,0 +1,216 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base.authorization; + +import static org.camunda.bpm.engine.authorization.Authorization.ANY; +import static org.camunda.bpm.engine.authorization.Authorization.AUTH_TYPE_GRANT; +import static org.camunda.bpm.engine.authorization.Permissions.ALL; +import static org.camunda.bpm.engine.authorization.Resources.AUTHORIZATION; +import static org.camunda.bpm.engine.authorization.Resources.USER; + +import java.util.Arrays; +import org.camunda.bpm.cockpit.plugin.test.AbstractCockpitPluginTest; +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.authorization.Authorization; +import org.camunda.bpm.engine.authorization.Permission; +import org.camunda.bpm.engine.authorization.Permissions; +import org.camunda.bpm.engine.authorization.Resource; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.repository.Deployment; +import org.camunda.bpm.engine.repository.DeploymentBuilder; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.junit.After; +import org.junit.Before; + +/** + * @author Roman Smirnov + * + */ +public abstract class AuthorizationTest extends AbstractCockpitPluginTest { + + protected ProcessEngine processEngine; + protected String engineName; + protected ProcessEngineConfigurationImpl processEngineConfiguration; + + protected IdentityService identityService; + protected AuthorizationService authorizationService; + protected RepositoryService repositoryService; + protected RuntimeService runtimeService; + + protected String userId = "test"; + protected String groupId = "accounting"; + protected User user; + protected Group group; + + @Before + public void setUp() throws Exception { + super.before(); + + processEngine = getProcessEngine(); + engineName = getProcessEngine().getName(); + processEngineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration(); + + identityService = processEngine.getIdentityService(); + authorizationService = processEngine.getAuthorizationService(); + repositoryService = processEngine.getRepositoryService(); + runtimeService = processEngine.getRuntimeService(); + + user = createUser(userId); + group = createGroup(groupId); + + identityService.createMembership(userId, groupId); + + identityService.setAuthentication(userId, Arrays.asList(groupId)); + enableAuthorization(); + } + + @After + public void tearDown() { + disableAuthorization(); + for (User user : identityService.createUserQuery().list()) { + identityService.deleteUser(user.getId()); + } + for (Group group : identityService.createGroupQuery().list()) { + identityService.deleteGroup(group.getId()); + } + for (Authorization authorization : authorizationService.createAuthorizationQuery().list()) { + authorizationService.deleteAuthorization(authorization.getId()); + } + } + + // user //////////////////////////////////////////////////////////////// + + protected User createUser(String userId) { + User user = identityService.newUser(userId); + identityService.saveUser(user); + + // give user all permission to manipulate authorizations + Authorization authorization = createGrantAuthorization(AUTHORIZATION, ANY); + authorization.setUserId(userId); + authorization.addPermission(ALL); + saveAuthorization(authorization); + + // give user all permission to manipulate users + authorization = createGrantAuthorization(USER, ANY); + authorization.setUserId(userId); + authorization.addPermission(Permissions.ALL); + saveAuthorization(authorization); + + return user; + } + + // group ////////////////////////////////////////////////////////////// + + protected Group createGroup(String groupId) { + Group group = identityService.newGroup(groupId); + identityService.saveGroup(group);; + return group; + } + + // authorization /////////////////////////////////////////////////////// + + protected void createGrantAuthorization(Resource resource, String resourceId, String userId, Permission... permissions) { + Authorization authorization = createGrantAuthorization(resource, resourceId); + authorization.setUserId(userId); + for (Permission permission : permissions) { + authorization.addPermission(permission); + } + saveAuthorization(authorization); + } + + protected Authorization createGrantAuthorization(Resource resource, String resourceId) { + Authorization authorization = createAuthorization(AUTH_TYPE_GRANT, resource, resourceId); + return authorization; + } + + protected Authorization createAuthorization(int type, Resource resource, String resourceId) { + Authorization authorization = authorizationService.createNewAuthorization(type); + + authorization.setResource(resource); + if (resourceId != null) { + authorization.setResourceId(resourceId); + } + + return authorization; + } + + protected void saveAuthorization(Authorization authorization) { + authorizationService.saveAuthorization(authorization); + } + + // enable/disable authorization ////////////////////////////////////////////// + + protected void enableAuthorization() { + processEngineConfiguration.setAuthorizationEnabled(true); + } + + protected void disableAuthorization() { + processEngineConfiguration.setAuthorizationEnabled(false); + } + + // actions (executed without authorization) /////////////////////////////////// + + protected ProcessDefinition selectProcessDefinitionByKey(String processDefinitionKey) { + disableAuthorization(); + ProcessDefinition definition = repositoryService + .createProcessDefinitionQuery() + .processDefinitionKey(processDefinitionKey) + .singleResult(); + enableAuthorization(); + return definition; + } + + protected ProcessInstance selectAnyProcessInstanceByKey(String processDefinitionKey) { + disableAuthorization(); + ProcessInstance instance = runtimeService.createProcessInstanceQuery().processDefinitionKey(processDefinitionKey).listPage(0, 1).get(0); + enableAuthorization(); + return instance; + } + + protected void startProcessInstances(String processDefinitionKey, int numOfInstances) { + disableAuthorization(); + for (int i = 0; i < numOfInstances; i++) { + runtimeService.startProcessInstanceByKey(processDefinitionKey, "businessKey_" + i); + } + enableAuthorization(); + } + + protected Deployment createDeployment(String name, String... resources) { + disableAuthorization(); + DeploymentBuilder builder = repositoryService.createDeployment(); + for (String resource : resources) { + builder.addClasspathResource(resource); + } + Deployment deployment = builder.deploy(); + enableAuthorization(); + return deployment; + } + + protected void deleteDeployment(String deploymentId) { + disableAuthorization(); + repositoryService.deleteDeployment(deploymentId, true); + enableAuthorization(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/IncidentRestServiceAuthorizationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/IncidentRestServiceAuthorizationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..18775321e5cfdadd795b6abed66aa76f9e63b055 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/IncidentRestServiceAuthorizationTest.java @@ -0,0 +1,147 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base.authorization; + +import static org.camunda.bpm.engine.authorization.Authorization.ANY; +import static org.camunda.bpm.engine.authorization.Permissions.READ; +import static org.camunda.bpm.engine.authorization.Permissions.READ_INSTANCE; +import static org.camunda.bpm.engine.authorization.Resources.PROCESS_DEFINITION; +import static org.camunda.bpm.engine.authorization.Resources.PROCESS_INSTANCE; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.IncidentDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.query.IncidentQueryDto; +import org.camunda.bpm.cockpit.impl.plugin.resources.IncidentRestService; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * @author Roman Smirnov + * + */ +public class IncidentRestServiceAuthorizationTest extends AuthorizationTest { + + protected static final String FAILING_PROCESS_KEY = "FailingProcess"; + + protected String deploymentId; + + protected IncidentRestService resource; + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + + runtimeService = processEngine.getRuntimeService(); + + deploymentId = createDeployment(null, "processes/failing-process.bpmn").getId(); + + resource = new IncidentRestService(engineName); + + startProcessInstances(FAILING_PROCESS_KEY, 3); + disableAuthorization(); + executeAvailableJobs(); + enableAuthorization(); + } + + @Override + @After + public void tearDown() { + deleteDeployment(deploymentId); + super.tearDown(); + } + + @Test + public void testQueryWithoutAuthorization() { + // given + IncidentQueryDto queryParameter = new IncidentQueryDto(); + + // when + List incidents = resource.queryIncidents(queryParameter, null, null); + + // then + assertThat(incidents).isEmpty(); + } + + @Test + public void testQueryWithReadPermissionOnProcessInstance() { + // given + String processInstanceId = selectAnyProcessInstanceByKey(FAILING_PROCESS_KEY).getId(); + createGrantAuthorization(PROCESS_INSTANCE, processInstanceId, userId, READ); + + IncidentQueryDto queryParameter = new IncidentQueryDto(); + + // when + List incidents = resource.queryIncidents(queryParameter, null, null); + + // then + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(1); + assertThat(incidents.get(0).getProcessInstanceId()).isEqualTo(processInstanceId); + } + + @Test + public void testQueryWithReadPermissionOnAnyProcessInstance() { + // given + createGrantAuthorization(PROCESS_INSTANCE, ANY, userId, READ); + + IncidentQueryDto queryParameter = new IncidentQueryDto(); + + // when + List incidents = resource.queryIncidents(queryParameter, null, null); + + // then + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(3); + } + + @Test + public void testQueryWithMultipleReadPermissions() { + // given + createGrantAuthorization(PROCESS_INSTANCE, ANY, userId, READ); + String processInstanceId = selectAnyProcessInstanceByKey(FAILING_PROCESS_KEY).getId(); + createGrantAuthorization(PROCESS_INSTANCE, processInstanceId, userId, READ); + + IncidentQueryDto queryParameter = new IncidentQueryDto(); + + // when + List incidents = resource.queryIncidents(queryParameter, null, null); + + // then + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(3); + } + + @Test + public void testQueryWithReadPermissionOnProcessDefinition() { + // given + createGrantAuthorization(PROCESS_DEFINITION, FAILING_PROCESS_KEY, userId, READ_INSTANCE); + + IncidentQueryDto queryParameter = new IncidentQueryDto(); + + // when + List incidents = resource.queryIncidents(queryParameter, null, null); + + // then + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(3); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/ProcessDefinitionResourceAuthorizationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/ProcessDefinitionResourceAuthorizationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..6aaab31496524eaded40d6ba7bba9d8851573b9c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/ProcessDefinitionResourceAuthorizationTest.java @@ -0,0 +1,203 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base.authorization; + +import static org.camunda.bpm.engine.authorization.Authorization.ANY; +import static org.camunda.bpm.engine.authorization.Permissions.READ; +import static org.camunda.bpm.engine.authorization.Permissions.READ_INSTANCE; +import static org.camunda.bpm.engine.authorization.Resources.PROCESS_DEFINITION; +import static org.camunda.bpm.engine.authorization.Resources.PROCESS_INSTANCE; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.ProcessDefinitionDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.query.ProcessDefinitionQueryDto; +import org.camunda.bpm.cockpit.impl.plugin.base.sub.resources.ProcessDefinitionResource; +import org.camunda.bpm.engine.test.Deployment; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * @author Roman Smirnov + * + */ +public class ProcessDefinitionResourceAuthorizationTest extends AuthorizationTest { + + protected static final String USER_TASK_PROCESS_KEY = "userTaskProcess"; + protected static final String CALLING_USER_TASK_PROCESS_KEY = "CallingUserTaskProcess"; + + protected String deploymentId; + + protected ProcessDefinitionResource resource; + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + + runtimeService = processEngine.getRuntimeService(); + + deploymentId = createDeployment(null, "processes/user-task-process.bpmn", "processes/calling-user-task-process.bpmn").getId(); + + startProcessInstances(CALLING_USER_TASK_PROCESS_KEY, 3); + } + + @Override + @After + public void tearDown() { + deleteDeployment(deploymentId); + super.tearDown(); + } + + @Test + public void testCalledProcessDefinitionQueryWithoutAuthorization() { + // given + String processDefinitionId = selectProcessDefinitionByKey(CALLING_USER_TASK_PROCESS_KEY).getId(); + resource = new ProcessDefinitionResource(engineName, processDefinitionId); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + + // when + List calledDefinitions = resource.queryCalledProcessDefinitions(queryParameter); + + // then + assertThat(calledDefinitions).isEmpty(); + } + + @Test + public void testCalledProcessDefinitionQueryWithReadPermissionOnProcessInstance() { + // given + String processDefinitionId = selectProcessDefinitionByKey(CALLING_USER_TASK_PROCESS_KEY).getId(); + resource = new ProcessDefinitionResource(engineName, processDefinitionId); + + String processInstanceId = selectAnyProcessInstanceByKey(CALLING_USER_TASK_PROCESS_KEY).getId(); + createGrantAuthorization(PROCESS_INSTANCE, processInstanceId, userId, READ); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + + // when + List calledDefinitions = resource.queryCalledProcessDefinitions(queryParameter); + + // then + assertThat(calledDefinitions).isNotEmpty(); + + ProcessDefinitionDto calledProcessDefinition = calledDefinitions.get(0); + assertThat(calledProcessDefinition.getKey()).isEqualTo(USER_TASK_PROCESS_KEY); + } + + @Test + public void testCalledProcessDefinitionQueryWithReadPermissionOnAnyProcessInstance() { + // given + String processDefinitionId = selectProcessDefinitionByKey(CALLING_USER_TASK_PROCESS_KEY).getId(); + resource = new ProcessDefinitionResource(engineName, processDefinitionId); + + createGrantAuthorization(PROCESS_INSTANCE, ANY, userId, READ); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + + // when + List calledDefinitions = resource.queryCalledProcessDefinitions(queryParameter); + + // then + assertThat(calledDefinitions).isNotEmpty(); + + ProcessDefinitionDto calledProcessDefinition = calledDefinitions.get(0); + assertThat(calledProcessDefinition.getKey()).isEqualTo(USER_TASK_PROCESS_KEY); + } + + @Test + public void testCalledProcessDefinitionQueryWithMultipleReadPermissions() { + // given + String processDefinitionId = selectProcessDefinitionByKey(CALLING_USER_TASK_PROCESS_KEY).getId(); + resource = new ProcessDefinitionResource(engineName, processDefinitionId); + + String processInstanceId = selectAnyProcessInstanceByKey(CALLING_USER_TASK_PROCESS_KEY).getId(); + createGrantAuthorization(PROCESS_INSTANCE, processInstanceId, userId, READ); + + createGrantAuthorization(PROCESS_INSTANCE, ANY, userId, READ); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + + // when + List calledDefinitions = resource.queryCalledProcessDefinitions(queryParameter); + + // then + assertThat(calledDefinitions.size()).isEqualTo(1); + + ProcessDefinitionDto calledProcessDefinition = calledDefinitions.get(0); + assertThat(calledProcessDefinition.getKey()).isEqualTo(USER_TASK_PROCESS_KEY); + } + + @Test + public void testCalledProcessDefinitionQueryWithReadInstancePermissionOnProcessDefinition() { + // given + String processDefinitionId = selectProcessDefinitionByKey(CALLING_USER_TASK_PROCESS_KEY).getId(); + resource = new ProcessDefinitionResource(engineName, processDefinitionId); + + createGrantAuthorization(PROCESS_DEFINITION, CALLING_USER_TASK_PROCESS_KEY, userId, READ_INSTANCE); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + + // when + List calledDefinitions = resource.queryCalledProcessDefinitions(queryParameter); + + // then + assertThat(calledDefinitions).isNotEmpty(); + + ProcessDefinitionDto calledProcessDefinition = calledDefinitions.get(0); + assertThat(calledProcessDefinition.getKey()).isEqualTo(USER_TASK_PROCESS_KEY); + } + + @Test + @Deployment(resources = { + "processes/another-user-task-process.bpmn", + "processes/dynamic-call-activity.bpmn" + }) + public void testCalledProcessDefinitionQueryDifferentCalledProcesses() { + // given + String processDefinitionId = selectProcessDefinitionByKey("DynamicCallActivity").getId(); + resource = new ProcessDefinitionResource(engineName, processDefinitionId); + + disableAuthorization(); + Map vars1 = new HashMap(); + vars1.put("callProcess", "anotherUserTaskProcess"); + String firstProcessInstanceId = runtimeService.startProcessInstanceByKey("DynamicCallActivity", vars1).getId(); + + Map vars2 = new HashMap(); + vars2.put("callProcess", "userTaskProcess"); + runtimeService.startProcessInstanceByKey("DynamicCallActivity", vars2); + enableAuthorization(); + + createGrantAuthorization(PROCESS_INSTANCE, firstProcessInstanceId, userId, READ); + + ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(); + + // when + List calledDefinitions = resource.queryCalledProcessDefinitions(queryParameter); + + // then + assertThat(calledDefinitions).isNotEmpty(); + + ProcessDefinitionDto calledProcessDefinition = calledDefinitions.get(0); + assertThat(calledProcessDefinition.getKey()).isEqualTo("anotherUserTaskProcess"); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/ProcessDefinitionRestServiceAuthorizationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/ProcessDefinitionRestServiceAuthorizationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..7fcdc334901e8c9dcc511eb8f7e05aa32a6eb6f4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/ProcessDefinitionRestServiceAuthorizationTest.java @@ -0,0 +1,177 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base.authorization; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.ProcessDefinitionStatisticsDto; +import org.camunda.bpm.cockpit.impl.plugin.resources.ProcessDefinitionRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; +import static org.camunda.bpm.engine.authorization.Authorization.ANY; +import static org.camunda.bpm.engine.authorization.Permissions.READ; +import static org.camunda.bpm.engine.authorization.Resources.PROCESS_DEFINITION; + +public class ProcessDefinitionRestServiceAuthorizationTest extends AuthorizationTest { + + private static final String USER_TASK_PROCESS_KEY = "userTaskProcess"; + private static final String CALLING_USER_TASK_PROCESS_KEY = "CallingUserTaskProcess"; + private String deploymentId; + private ProcessDefinitionRestService resource; + private UriInfo uriInfo; + private final MultivaluedMap queryParameters = new MultivaluedHashMap<>(); + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + + resource = new ProcessDefinitionRestService(engineName); + runtimeService = processEngine.getRuntimeService(); + + deploymentId = createDeployment(null, "processes/user-task-process.bpmn", "processes/calling-user-task-process.bpmn").getId(); + + startProcessInstances(CALLING_USER_TASK_PROCESS_KEY, 3); + + uriInfo = Mockito.mock(UriInfo.class); + Mockito.doReturn(queryParameters).when(uriInfo).getQueryParameters(); + queryParameters.add("sortBy", "key"); + queryParameters.add("sortOrder", "asc"); + } + + @Override + @After + public void tearDown() { + queryParameters.clear(); + deleteDeployment(deploymentId); + super.tearDown(); + } + + @Test + public void queryStatisticsWithoutAuthorization() { + // when + List actual = resource.queryStatistics(uriInfo, null, null); + + // then + assertThat(actual).isEmpty(); + } + + @Test + public void queryStatisticsWithReadPermissionOnProcessDefinition() { + // given + String key = selectProcessDefinitionByKey(CALLING_USER_TASK_PROCESS_KEY).getKey(); + createGrantAuthorization(PROCESS_DEFINITION, key, userId, READ); + + // when + List actual = resource.queryStatistics(uriInfo, null, null); + + // then + assertThat(actual).hasSize(1); + assertThat(actual).extracting("key", "tenantId") + .containsOnly(tuple(CALLING_USER_TASK_PROCESS_KEY, null)); + } + + @Test + public void queryStatisticsWithReadPermissionOnAnyProcessDefinition() { + // given + createGrantAuthorization(PROCESS_DEFINITION, ANY, userId, READ); + + // when + List actual = resource.queryStatistics(uriInfo, null, null); + + // then + assertThat(actual).hasSize(2); + assertThat(actual).extracting("key", "tenantId") + .containsOnly(tuple(CALLING_USER_TASK_PROCESS_KEY, null), + tuple(USER_TASK_PROCESS_KEY, null)); + } + + @Test + public void queryStatisticsWithMultipleReadPermissions() { + // given + String key = selectProcessDefinitionByKey(CALLING_USER_TASK_PROCESS_KEY).getKey(); + createGrantAuthorization(PROCESS_DEFINITION, key, userId, READ); + createGrantAuthorization(PROCESS_DEFINITION, ANY, userId, READ); + + // when + List actual = resource.queryStatistics(uriInfo, null, null); + + // then + assertThat(actual).hasSize(2); + assertThat(actual).extracting("key", "tenantId") + .containsOnly(tuple(CALLING_USER_TASK_PROCESS_KEY, null), + tuple(USER_TASK_PROCESS_KEY, null)); + } + + @Test + public void getStatisticsCountWithoutAuthorization() { + // when + CountResultDto actual = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual.getCount()).isEqualTo(0); + } + + @Test + public void getStatisticsCountWithReadPermissionOnProcessDefinition() { + // given + String key = selectProcessDefinitionByKey(CALLING_USER_TASK_PROCESS_KEY).getKey(); + createGrantAuthorization(PROCESS_DEFINITION, key, userId, READ); + + // when + CountResultDto actual = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual.getCount()).isEqualTo(1); + } + + @Test + public void getStatisticsCountWithReadPermissionOnAnyProcessDefinition() { + // given + createGrantAuthorization(PROCESS_DEFINITION, ANY, userId, READ); + + // when + CountResultDto actual = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual.getCount()).isEqualTo(2); + } + + @Test + public void getStatisticsCountWithMultipleReadPermissions() { + // given + String key = selectProcessDefinitionByKey(CALLING_USER_TASK_PROCESS_KEY).getKey(); + createGrantAuthorization(PROCESS_DEFINITION, key, userId, READ); + createGrantAuthorization(PROCESS_DEFINITION, ANY, userId, READ); + + // when + CountResultDto actual = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual.getCount()).isEqualTo(2); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/ProcessInstanceResourceAuthorizationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/ProcessInstanceResourceAuthorizationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..cf433e4bf7bbbfcbdc00a7a5269c00677a50f244 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/ProcessInstanceResourceAuthorizationTest.java @@ -0,0 +1,276 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base.authorization; + +import static org.camunda.bpm.engine.authorization.Authorization.ANY; +import static org.camunda.bpm.engine.authorization.Permissions.READ; +import static org.camunda.bpm.engine.authorization.Permissions.READ_INSTANCE; +import static org.camunda.bpm.engine.authorization.Resources.PROCESS_DEFINITION; +import static org.camunda.bpm.engine.authorization.Resources.PROCESS_INSTANCE; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.CalledProcessInstanceDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.query.CalledProcessInstanceQueryDto; +import org.camunda.bpm.cockpit.impl.plugin.base.sub.resources.ProcessInstanceResource; +import org.camunda.bpm.engine.impl.db.AuthorizationCheck; +import org.camunda.bpm.engine.impl.db.PermissionCheck; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * @author Roman Smirnov + * + */ +public class ProcessInstanceResourceAuthorizationTest extends AuthorizationTest { + + protected static final String USER_TASK_PROCESS_KEY = "userTaskProcess"; + protected static final String CALLING_USER_TASK_PROCESS_KEY = "CallingUserTaskProcess"; + + protected String deploymentId; + + protected ProcessInstanceResource resource; + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + + runtimeService = processEngine.getRuntimeService(); + + deploymentId = createDeployment(null, "processes/user-task-process.bpmn", "processes/calling-user-task-process.bpmn").getId(); + + startProcessInstances(CALLING_USER_TASK_PROCESS_KEY, 3); + } + + @Override + @After + public void tearDown() { + deleteDeployment(deploymentId); + super.tearDown(); + } + + // ProcessInstanceResource#queryCalledProcessInstances() ///////////////////////////// + + @Test + public void testCalledInstancesWithoutAuthorization() { + // given + String processInstanceId = selectAnyProcessInstanceByKey(CALLING_USER_TASK_PROCESS_KEY).getId(); + + resource = new ProcessInstanceResource(engineName, processInstanceId); + + CalledProcessInstanceQueryDto queryParameter = new CalledProcessInstanceQueryDto(); + + // when + List calledInstances = resource.queryCalledProcessInstances(queryParameter); + + // then + assertThat(calledInstances).isEmpty(); + } + + @Test + public void testCalledInstancesWithReadPermissionOnProcessInstance() { + // given + String processInstanceId = selectAnyProcessInstanceByKey(CALLING_USER_TASK_PROCESS_KEY).getId(); + createGrantAuthorization(PROCESS_INSTANCE, processInstanceId, userId, READ); + + resource = new ProcessInstanceResource(engineName, processInstanceId); + + CalledProcessInstanceQueryDto queryParameter = new CalledProcessInstanceQueryDto(); + + // when + List calledInstances = resource.queryCalledProcessInstances(queryParameter); + + // then + assertThat(calledInstances).isNotEmpty(); + assertThat(calledInstances).hasSize(1); + assertThat(calledInstances.get(0).getId()).isNotEqualTo(processInstanceId); + } + + @Test + public void testCalledInstancesWithReadPermissionOnAnyProcessInstance() { + // given + String processInstanceId = selectAnyProcessInstanceByKey(CALLING_USER_TASK_PROCESS_KEY).getId(); + createGrantAuthorization(PROCESS_INSTANCE, processInstanceId, userId, READ); + + resource = new ProcessInstanceResource(engineName, processInstanceId); + + CalledProcessInstanceQueryDto queryParameter = new CalledProcessInstanceQueryDto(); + + // when + List calledInstances = resource.queryCalledProcessInstances(queryParameter); + + // then + assertThat(calledInstances).isNotEmpty(); + assertThat(calledInstances).hasSize(1); + assertThat(calledInstances.get(0).getId()).isNotEqualTo(processInstanceId); + } + + @Test + public void testCalledInstancesWithReadPermissionOnProcessDefinition() { + // given + createGrantAuthorization(PROCESS_DEFINITION, CALLING_USER_TASK_PROCESS_KEY, userId, READ_INSTANCE); + + String processInstanceId = selectAnyProcessInstanceByKey(CALLING_USER_TASK_PROCESS_KEY).getId(); + resource = new ProcessInstanceResource(engineName, processInstanceId); + + CalledProcessInstanceQueryDto queryParameter = new CalledProcessInstanceQueryDto(); + + // when + List calledInstances = resource.queryCalledProcessInstances(queryParameter); + + // then + assertThat(calledInstances).isNotEmpty(); + assertThat(calledInstances).hasSize(1); + assertThat(calledInstances.get(0).getId()).isNotEqualTo(processInstanceId); + } + + @Test + public void testCalledInstancesWithMultipleReadPermissions() { + // given + String processInstanceId = selectAnyProcessInstanceByKey(CALLING_USER_TASK_PROCESS_KEY).getId(); + createGrantAuthorization(PROCESS_DEFINITION, CALLING_USER_TASK_PROCESS_KEY, userId, READ_INSTANCE); + createGrantAuthorization(PROCESS_INSTANCE, processInstanceId, userId, READ); + + resource = new ProcessInstanceResource(engineName, processInstanceId); + + CalledProcessInstanceQueryDto queryParameter = new CalledProcessInstanceQueryDto(); + + // when + List calledInstances = resource.queryCalledProcessInstances(queryParameter); + + // then + assertThat(calledInstances).isNotEmpty(); + assertThat(calledInstances).hasSize(1); + assertThat(calledInstances.get(0).getId()).isNotEqualTo(processInstanceId); + } + + + // query "selectCalledProcessInstances" ////////////////////////////////////////////// + + @Test + public void testCalledInstancesQueryWithoutAuthorization() { + // given + CalledProcessInstanceQueryDto queryParameter = new CalledProcessInstanceQueryDto(); + + // when + List calledInstances = executeCalledInstancesQueryWithAuthorization(queryParameter); + + // then + assertThat(calledInstances).isEmpty(); + } + + @Test + public void testCalledInstancesQueryWithReadPermissionOnProcessInstance() { + // given + String processInstanceId = selectAnyProcessInstanceByKey(CALLING_USER_TASK_PROCESS_KEY).getId(); + createGrantAuthorization(PROCESS_INSTANCE, processInstanceId, userId, READ); + + CalledProcessInstanceQueryDto queryParameter = new CalledProcessInstanceQueryDto(); + + // when + List calledInstances = executeCalledInstancesQueryWithAuthorization(queryParameter); + + // then + assertThat(calledInstances).isNotEmpty(); + assertThat(calledInstances).hasSize(1); + assertThat(calledInstances.get(0).getId()).isNotEqualTo(processInstanceId); + } + + @Test + public void testCalledInstancesQueryWithReadPermissionOnAnyProcessInstance() { + // given + createGrantAuthorization(PROCESS_INSTANCE, ANY, userId, READ); + + CalledProcessInstanceQueryDto queryParameter = new CalledProcessInstanceQueryDto(); + + // when + List calledInstances = executeCalledInstancesQueryWithAuthorization(queryParameter); + + // then + assertThat(calledInstances).isNotEmpty(); + assertThat(calledInstances).hasSize(3); + } + + @Test + public void testCalledInstancesQueryWithReadInstancePermissionOnProcessDefinition() { + // given + createGrantAuthorization(PROCESS_DEFINITION, CALLING_USER_TASK_PROCESS_KEY, userId, READ_INSTANCE); + + CalledProcessInstanceQueryDto queryParameter = new CalledProcessInstanceQueryDto(); + + // when + List calledInstances = executeCalledInstancesQueryWithAuthorization(queryParameter); + + // then + assertThat(calledInstances).isNotEmpty(); + assertThat(calledInstances).hasSize(3); + } + + @Test + public void testCalledInstancesQueryWithMultipleReadPermissins() { + // given + createGrantAuthorization(PROCESS_DEFINITION, CALLING_USER_TASK_PROCESS_KEY, userId, READ_INSTANCE); + createGrantAuthorization(PROCESS_INSTANCE, ANY, userId, READ); + + CalledProcessInstanceQueryDto queryParameter = new CalledProcessInstanceQueryDto(); + + // when + List calledInstances = executeCalledInstancesQueryWithAuthorization(queryParameter); + + // then + assertThat(calledInstances).isNotEmpty(); + assertThat(calledInstances).hasSize(3); + } + + // helper //////////////////////////////////////////////////////////////////////////// + + protected Authentication getCurrentAuthentication() { + return identityService.getCurrentAuthentication(); + } + + protected List executeCalledInstancesQueryWithAuthorization(CalledProcessInstanceQueryDto query) { + Authentication currentAuthentication = getCurrentAuthentication(); + + AuthorizationCheck authCheck = query.getAuthCheck(); + + authCheck.getPermissionChecks().clear(); + authCheck.setAuthorizationCheckEnabled(true); + String currentUserId = currentAuthentication.getUserId(); + List currentGroupIds = currentAuthentication.getGroupIds(); + authCheck.setAuthUserId(currentUserId); + authCheck.setAuthGroupIds(currentGroupIds); + + PermissionCheck firstPermCheck = new PermissionCheck(); + firstPermCheck.setResource(PROCESS_INSTANCE); + firstPermCheck.setResourceIdQueryParam("EXEC1.PROC_INST_ID_"); + firstPermCheck.setPermission(READ); + authCheck.addAtomicPermissionCheck(firstPermCheck); + + PermissionCheck secondPermCheck = new PermissionCheck(); + secondPermCheck.setResource(PROCESS_DEFINITION); + secondPermCheck.setResourceIdQueryParam("PROCDEF.KEY_"); + secondPermCheck.setPermission(READ_INSTANCE); + authCheck.addAtomicPermissionCheck(secondPermCheck); + + return getQueryService().executeQuery("selectCalledProcessInstances", query); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/ProcessInstanceRestServiceAuthorizationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/ProcessInstanceRestServiceAuthorizationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..a04c0828441237d12ca087e77a4373e3ebec1fce --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/authorization/ProcessInstanceRestServiceAuthorizationTest.java @@ -0,0 +1,150 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base.authorization; + +import static org.camunda.bpm.engine.authorization.Authorization.ANY; +import static org.camunda.bpm.engine.authorization.Permissions.READ; +import static org.camunda.bpm.engine.authorization.Permissions.READ_INSTANCE; +import static org.camunda.bpm.engine.authorization.Resources.PROCESS_DEFINITION; +import static org.camunda.bpm.engine.authorization.Resources.PROCESS_INSTANCE; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.ProcessInstanceDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.query.ProcessInstanceQueryDto; +import org.camunda.bpm.cockpit.impl.plugin.resources.ProcessInstanceRestService; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * @author Roman Smirnov + * + */ +public class ProcessInstanceRestServiceAuthorizationTest extends AuthorizationTest { + + protected static final String USER_TASK_PROCESS_KEY = "userTaskProcess"; + + protected String deploymentId; + + protected ProcessInstanceRestService resource; + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + + deploymentId = createDeployment(null, "processes/user-task-process.bpmn").getId(); + + startProcessInstances(USER_TASK_PROCESS_KEY, 3); + + resource = new ProcessInstanceRestService(engineName); + } + + @Override + @After + public void tearDown() { + deleteDeployment(deploymentId); + super.tearDown(); + } + + @Test + public void testQueryWithoutAuthorization() { + // given + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + // when + List instances = resource.queryProcessInstances(queryParameter, null, null); + + // then + assertThat(instances).isEmpty(); + } + + @Test + public void testQueryWithReadPermissionOnProcessInstance() { + // given + String processInstanceId = selectAnyProcessInstanceByKey(USER_TASK_PROCESS_KEY).getId(); + + createGrantAuthorization(PROCESS_INSTANCE, processInstanceId, userId, READ); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + // when + List instances = resource.queryProcessInstances(queryParameter, null, null); + + // then + assertThat(instances).isNotEmpty(); + assertThat(instances).hasSize(1); + assertThat(instances.get(0).getId()).isEqualTo(processInstanceId); + } + + @Test + public void testQueryWithReadPermissionOnAnyProcessInstance() { + // given + createGrantAuthorization(PROCESS_INSTANCE, ANY, userId, READ); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + // when + List instances = resource.queryProcessInstances(queryParameter, null, null); + + // then + assertThat(instances).isNotEmpty(); + assertThat(instances).hasSize(3); + } + + @Test + public void testQueryWithReadInstancePermissionOnProcessDefinition() { + // given + createGrantAuthorization(PROCESS_DEFINITION, USER_TASK_PROCESS_KEY, userId, READ_INSTANCE); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + // when + List instances = resource.queryProcessInstances(queryParameter, null, null); + + // then + assertThat(instances).isNotEmpty(); + assertThat(instances).hasSize(3); + } + + @Test + public void testQueryPaginationWithOverlappingPermissions() { + // given + createGrantAuthorization(PROCESS_DEFINITION, USER_TASK_PROCESS_KEY, userId, READ_INSTANCE); + createGrantAuthorization(PROCESS_INSTANCE, ANY, userId, READ); + + ProcessInstanceQueryDto queryParameter = new ProcessInstanceQueryDto(); + + // when + List result = resource.queryProcessInstances(queryParameter, 0, 3); + + // then + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(3); + + result = resource.queryProcessInstances(queryParameter, 0, 2); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + result = resource.queryProcessInstances(queryParameter, 2, 2); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/pa/CreateIncidentsDelegate.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/pa/CreateIncidentsDelegate.java new file mode 100644 index 0000000000000000000000000000000000000000..97fc738e001eabe6440bbee2f81774cd634a1231 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/pa/CreateIncidentsDelegate.java @@ -0,0 +1,50 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base.pa; + +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.camunda.bpm.engine.delegate.JavaDelegate; +import org.camunda.bpm.engine.impl.incident.IncidentContext; +import org.camunda.bpm.engine.impl.persistence.entity.IncidentEntity; + +public class CreateIncidentsDelegate implements JavaDelegate { + + @Override + public void execute(DelegateExecution execution) throws Exception { + + IncidentEntity.createAndInsertIncident("anIncident", createIncidentContext(execution, "test1"), "aMessage"); + IncidentEntity.createAndInsertIncident("anIncident", createIncidentContext(execution, "test2"), "aMessage"); + IncidentEntity.createAndInsertIncident("anIncident", createIncidentContext(execution, "test3"), "aMessage"); + + IncidentEntity.createAndInsertIncident("anotherIncident", createIncidentContext(execution, "test1"), "anotherMessage"); + IncidentEntity.createAndInsertIncident("anotherIncident", createIncidentContext(execution, "test2"), "anotherMessage"); + IncidentEntity.createAndInsertIncident("anotherIncident", createIncidentContext(execution, "test3"), "anotherMessage"); + IncidentEntity.createAndInsertIncident("anotherIncident", createIncidentContext(execution, "test4"), "anotherMessage"); + IncidentEntity.createAndInsertIncident("anotherIncident", createIncidentContext(execution, "test5"), "anotherMessage"); + } + + private IncidentContext createIncidentContext(DelegateExecution execution, String configuration) { + IncidentContext incidentContext = new IncidentContext(); + incidentContext.setExecutionId(execution.getId()); + incidentContext.setActivityId(execution.getCurrentActivityId()); + incidentContext.setProcessDefinitionId(execution.getProcessDefinitionId()); + incidentContext.setTenantId(execution.getTenantId()); + incidentContext.setConfiguration(configuration); + return incidentContext; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/pa/FailingDelegate.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/pa/FailingDelegate.java new file mode 100644 index 0000000000000000000000000000000000000000..6d1a180ebd0bdef347b7b591292dd3e83f1f8356 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/pa/FailingDelegate.java @@ -0,0 +1,29 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base.pa; + +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.camunda.bpm.engine.delegate.JavaDelegate; + +public class FailingDelegate implements JavaDelegate { + + @Override + public void execute(DelegateExecution execution) throws Exception { + throw new RuntimeException("I am failing!"); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/pa/VariableSavingDelegate.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/pa/VariableSavingDelegate.java new file mode 100644 index 0000000000000000000000000000000000000000..cce8ec896debd30543c589d9a99448082931b7a5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/pa/VariableSavingDelegate.java @@ -0,0 +1,33 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base.pa; + +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.camunda.bpm.engine.delegate.JavaDelegate; + +public class VariableSavingDelegate implements JavaDelegate { + + @Override + public void execute(DelegateExecution execution) throws Exception { + + execution.setVariable("varstring", "FOO"); + execution.setVariable("varstring2", "F_OO"); + execution.setVariable("varinteger", 12); + execution.setVariable("varfloat", 12.12); + execution.setVariable("varboolean", true); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/IncidentRestServiceTenantCheckTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/IncidentRestServiceTenantCheckTest.java new file mode 100644 index 0000000000000000000000000000000000000000..350144621e57e5c35c5325f45fca3d1d9b19aa82 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/IncidentRestServiceTenantCheckTest.java @@ -0,0 +1,187 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base.tenantcheck; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.IncidentDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.query.IncidentQueryDto; +import org.camunda.bpm.cockpit.impl.plugin.resources.IncidentRestService; +import org.camunda.bpm.cockpit.plugin.test.AbstractCockpitPluginTest; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.authorization.Groups; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class IncidentRestServiceTenantCheckTest extends AbstractCockpitPluginTest { + + protected static final String TENANT_ONE = "tenant1"; + protected static final String TENANT_TWO = "tenant2"; + protected static final String ADMIN_GROUP = "adminGroup"; + protected static final String ADMIN_USER = "adminUser"; + + private ProcessEngine processEngine; + private ProcessEngineConfigurationImpl processEngineConfiguration; + private RuntimeService runtimeService; + private IdentityService identityService; + + private IncidentRestService resource; + private IncidentQueryDto queryParameter; + + private String processInstanceTenantOne; + private String processInstanceTenantTwo; + + @Before + public void init() throws Exception { + + processEngine = getProcessEngine(); + processEngineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration(); + + runtimeService = processEngine.getRuntimeService(); + identityService = processEngine.getIdentityService(); + + processEngineConfiguration.getAdminGroups().add(ADMIN_GROUP); + processEngineConfiguration.getAdminUsers().add(ADMIN_USER); + + resource = new IncidentRestService(processEngine.getName()); + + deployForTenant(TENANT_ONE, "processes/failing-process.bpmn"); + deployForTenant(TENANT_TWO, "processes/failing-process.bpmn"); + + processInstanceTenantOne = runtimeService.createProcessInstanceByKey("FailingProcess") + .processDefinitionTenantId(TENANT_ONE).execute().getId(); + + processInstanceTenantTwo = runtimeService.createProcessInstanceByKey("FailingProcess") + .processDefinitionTenantId(TENANT_TWO).execute().getId(); + + executeAvailableJobs(); + + queryParameter = new IncidentQueryDto(); + queryParameter.setProcessInstanceIdIn(new String[]{processInstanceTenantOne, processInstanceTenantTwo}); + } + + @After + public void tearDown() { + processEngineConfiguration.getAdminGroups().remove(ADMIN_GROUP); + processEngineConfiguration.getAdminUsers().remove(ADMIN_USER); + } + + @Test + public void queryIncidentsByProcessInstanceIdsNoAuthenticatedTenants() { + + identityService.setAuthentication("user", null, null); + + List result = resource.queryIncidents(queryParameter, null, null); + assertThat(result).isEmpty(); + } + + @Test + public void queryIncidentsByProcessInstanceIdsWithAuthenticatedTenant() { + + identityService.setAuthentication("user", null, Arrays.asList(TENANT_ONE)); + + List result = resource.queryIncidents(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + IncidentDto incident = result.get(0); + assertThat(incident.getProcessInstanceId()).isEqualTo(processInstanceTenantOne); + } + + @Test + public void queryIncidentsByProcessInstanceIdsDisabledTenantCheck() { + + processEngineConfiguration.setTenantCheckEnabled(false); + identityService.setAuthentication("user", null, null); + + List result = resource.queryIncidents(queryParameter, null, null); + assertThat(result).hasSize(2); + + Set processInstnaceIds = new HashSet<>(); + for (IncidentDto incidentDto : result) { + processInstnaceIds.add(incidentDto.getProcessInstanceId()); + } + + assertThat(processInstnaceIds).contains(processInstanceTenantOne); + assertThat(processInstnaceIds).contains(processInstanceTenantTwo); + } + + @Test + public void queryIncidentsByProcessInstanceIdsWithCamundaAdmin() { + + identityService.setAuthentication("user", Collections.singletonList(Groups.CAMUNDA_ADMIN), null); + + + List result = resource.queryIncidents(queryParameter, null, null); + assertThat(result).hasSize(2); + + Set processInstnaceIds = new HashSet<>(); + for (IncidentDto incidentDto : result) { + processInstnaceIds.add(incidentDto.getProcessInstanceId()); + } + + assertThat(processInstnaceIds).contains(processInstanceTenantOne); + assertThat(processInstnaceIds).contains(processInstanceTenantTwo); + } + + @Test + public void queryIncidentsByProcessInstanceIdsWithAdminGroups() { + + identityService.setAuthentication("user", Collections.singletonList(ADMIN_GROUP), null); + + + List result = resource.queryIncidents(queryParameter, null, null); + assertThat(result).hasSize(2); + + Set processInstnaceIds = new HashSet<>(); + for (IncidentDto incidentDto : result) { + processInstnaceIds.add(incidentDto.getProcessInstanceId()); + } + + assertThat(processInstnaceIds).contains(processInstanceTenantOne); + assertThat(processInstnaceIds).contains(processInstanceTenantTwo); + } + + @Test + public void queryIncidentsByProcessInstanceIdsWithAdminUsers() { + + identityService.setAuthentication("adminUser", null, null); + + + List result = resource.queryIncidents(queryParameter, null, null); + assertThat(result).hasSize(2); + + Set processInstnaceIds = new HashSet<>(); + for (IncidentDto incidentDto : result) { + processInstnaceIds.add(incidentDto.getProcessInstanceId()); + } + + assertThat(processInstnaceIds).contains(processInstanceTenantOne); + assertThat(processInstnaceIds).contains(processInstanceTenantTwo); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/ProcessDefinitionResourceTenantCheckTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/ProcessDefinitionResourceTenantCheckTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ec641205b9f553ccb8cce97b233c010f9d1d30e8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/ProcessDefinitionResourceTenantCheckTest.java @@ -0,0 +1,166 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base.tenantcheck; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.ProcessDefinitionDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.query.ProcessDefinitionQueryDto; +import org.camunda.bpm.cockpit.impl.plugin.base.sub.resources.ProcessDefinitionResource; +import org.camunda.bpm.cockpit.plugin.test.AbstractCockpitPluginTest; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.authorization.Groups; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ProcessDefinitionResourceTenantCheckTest extends AbstractCockpitPluginTest { + + protected static final String TENANT_ONE = "tenant1"; + protected static final String TENANT_TWO = "tenant2"; + protected static final String ADMIN_GROUP = "adminGroup"; + protected static final String ADMIN_USER = "adminUser"; + + private ProcessEngine processEngine; + private ProcessEngineConfigurationImpl processEngineConfiguration; + private RuntimeService runtimeService; + private IdentityService identityService; + + private ProcessDefinitionResource resource; + private ProcessDefinitionQueryDto queryParameter; + + @Before + public void init() throws Exception { + + processEngine = getProcessEngine(); + processEngineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration(); + + runtimeService = processEngine.getRuntimeService(); + identityService = processEngine.getIdentityService(); + + processEngineConfiguration.getAdminGroups().add(ADMIN_GROUP); + processEngineConfiguration.getAdminUsers().add(ADMIN_USER); + + deploy("processes/multi-tenancy-call-activity.bpmn"); + deployForTenant(TENANT_ONE, "processes/user-task-process.bpmn"); + deployForTenant(TENANT_TWO, "processes/user-task-process.bpmn"); + + + ProcessInstance processInstance = runtimeService.createProcessInstanceByKey("multiTenancyCallActivity").execute(); + + resource = new ProcessDefinitionResource(getProcessEngine().getName(), processInstance.getProcessDefinitionId()); + + queryParameter = new ProcessDefinitionQueryDto(); + } + + @After + public void tearDown() { + processEngineConfiguration.getAdminGroups().remove(ADMIN_GROUP); + processEngineConfiguration.getAdminUsers().remove(ADMIN_USER); + } + + @Test + public void calledProcessDefinitionByParentProcessDefinitionIdNoAuthenticatedTenant() { + + identityService.setAuthentication("user", null, null); + + List result = resource.queryCalledProcessDefinitions(queryParameter); + assertThat(result).isEmpty(); + } + + @Test + public void calledProcessDefinitionByParentProcessDefinitionIdWithAuthenticatedTenant() { + + identityService.setAuthentication("user", null, Arrays.asList(TENANT_ONE)); + + List result = resource.queryCalledProcessDefinitions(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + assertThat(getCalledFromActivityIds(result)).containsOnly("CallActivity_Tenant1"); + } + + @Test + public void calledProcessDefinitionByParentProcessDefinitionIdDisabledTenantCheck() { + + processEngineConfiguration.setTenantCheckEnabled(false); + identityService.setAuthentication("user", null, null); + + List result = resource.queryCalledProcessDefinitions(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + assertThat(getCalledFromActivityIds(result)).contains("CallActivity_Tenant1", "CallActivity_Tenant2"); + } + + @Test + public void calledProcessDefinitionByParentProcessDefinitionIdWithCamundaAdmin() { + + identityService.setAuthentication("user", Collections.singletonList(Groups.CAMUNDA_ADMIN), null); + + List result = resource.queryCalledProcessDefinitions(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + assertThat(getCalledFromActivityIds(result)).contains("CallActivity_Tenant1", "CallActivity_Tenant2"); + } + + @Test + public void calledProcessDefinitionByParentProcessDefinitionIdWithAdminGroups() { + + identityService.setAuthentication("user", Collections.singletonList(ADMIN_GROUP), null); + + List result = resource.queryCalledProcessDefinitions(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + assertThat(getCalledFromActivityIds(result)).contains("CallActivity_Tenant1", "CallActivity_Tenant2"); + } + + @Test + public void calledProcessDefinitionByParentProcessDefinitionIdWithAdminUsers() { + + identityService.setAuthentication("adminUser", null, null); + + List result = resource.queryCalledProcessDefinitions(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + assertThat(getCalledFromActivityIds(result)).contains("CallActivity_Tenant1", "CallActivity_Tenant2"); + } + + protected List getCalledFromActivityIds(List processDefinitions) { + List activityIds = new ArrayList<>(); + + for (ProcessDefinitionDto processDefinition : processDefinitions) { + activityIds.addAll(processDefinition.getCalledFromActivityIds()); + } + + return activityIds; + } + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/ProcessDefinitionRestServiceTenantCheckTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/ProcessDefinitionRestServiceTenantCheckTest.java new file mode 100644 index 0000000000000000000000000000000000000000..e73de6d800d0791200e7f1cd86a8496a48875004 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/ProcessDefinitionRestServiceTenantCheckTest.java @@ -0,0 +1,251 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base.tenantcheck; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.ProcessDefinitionStatisticsDto; +import org.camunda.bpm.cockpit.impl.plugin.resources.ProcessDefinitionRestService; +import org.camunda.bpm.cockpit.plugin.test.AbstractCockpitPluginTest; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.authorization.Groups; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; + +public class ProcessDefinitionRestServiceTenantCheckTest extends AbstractCockpitPluginTest { + + protected static final String TENANT_ONE = "tenant1"; + protected static final String TENANT_TWO = "tenant2"; + protected static final String ADMIN_GROUP = "adminGroup"; + protected static final String ADMIN_USER = "adminUser"; + + private ProcessEngineConfigurationImpl processEngineConfiguration; + private IdentityService identityService; + private ProcessDefinitionRestService resource; + private UriInfo uriInfo; + private final MultivaluedMap queryParameters = new MultivaluedHashMap<>(); + + @Before + public void init() throws Exception { + + ProcessEngine processEngine = getProcessEngine(); + processEngineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration(); + + identityService = processEngine.getIdentityService(); + + processEngineConfiguration.getAdminGroups().add(ADMIN_GROUP); + processEngineConfiguration.getAdminUsers().add(ADMIN_USER); + + deploy("processes/multi-tenancy-call-activity.bpmn"); + deployForTenant(TENANT_ONE, "processes/user-task-process.bpmn"); + deployForTenant(TENANT_TWO, "processes/user-task-process.bpmn"); + + resource = new ProcessDefinitionRestService(getProcessEngine().getName()); + + uriInfo = Mockito.mock(UriInfo.class); + Mockito.doReturn(queryParameters).when(uriInfo).getQueryParameters(); + queryParameters.add("sortBy", "tenantId"); + queryParameters.add("sortOrder", "asc"); + } + + @After + public void tearDown() { + processEngineConfiguration.getAdminGroups().remove(ADMIN_GROUP); + processEngineConfiguration.getAdminUsers().remove(ADMIN_USER); + queryParameters.clear(); + } + + @Test + public void queryStatisticsNoAuthenticatedTenant() { + // given + identityService.setAuthentication("user", null, null); + + // when + List actual = resource.queryStatistics(uriInfo, null, null); + + // then + assertThat(actual).hasSize(1); + assertThat(actual).extracting("key", "tenantId") + .containsOnly(tuple("multiTenancyCallActivity", null)); + } + + @Test + public void queryStatisticsWithAuthenticatedTenant() { + // given + identityService.setAuthentication("user", null, Collections.singletonList(TENANT_ONE)); + + // when + List actual = resource.queryStatistics(uriInfo, null, null); + + // then + assertThat(actual).hasSize(2); + assertThat(actual).extracting("key", "tenantId") + .containsOnly(tuple("multiTenancyCallActivity", null), + tuple("userTaskProcess", TENANT_ONE)); + } + + @Test + public void queryStatisticsWithDisabledTenantCheck() { + // given + processEngineConfiguration.setTenantCheckEnabled(false); + identityService.setAuthentication("user", null, null); + + // when + List actual = resource.queryStatistics(uriInfo, null, null); + + // then + assertThat(actual).hasSize(3); + assertThat(actual).extracting("key", "tenantId") + .containsOnly(tuple("multiTenancyCallActivity", null), + tuple("userTaskProcess", TENANT_ONE), + tuple("userTaskProcess", TENANT_TWO)); + } + + @Test + public void queryStatisticsWithCamundaAdmin() { + // given + identityService.setAuthentication("user", Collections.singletonList(Groups.CAMUNDA_ADMIN), null); + + // when + List actual = resource.queryStatistics(uriInfo, null, null); + + // then + assertThat(actual).hasSize(3); + assertThat(actual).extracting("key", "tenantId") + .containsOnly(tuple("multiTenancyCallActivity", null), + tuple("userTaskProcess", TENANT_ONE), + tuple("userTaskProcess", TENANT_TWO)); + } + + @Test + public void queryStatisticsWithAdminGroups() { + // given + identityService.setAuthentication("user", Collections.singletonList(ADMIN_GROUP), null); + + // when + List actual = resource.queryStatistics(uriInfo, null, null); + + // then + assertThat(actual).hasSize(3); + assertThat(actual).extracting("key", "tenantId") + .containsOnly(tuple("multiTenancyCallActivity", null), + tuple("userTaskProcess", TENANT_ONE), + tuple("userTaskProcess", TENANT_TWO)); + } + + @Test + public void queryStatisticsWithAdminUsers() { + // given + identityService.setAuthentication("adminUser", null, null); + + // when + List actual = resource.queryStatistics(uriInfo, null, null); + + // then + assertThat(actual).hasSize(3); + assertThat(actual).extracting("key", "tenantId") + .containsOnly(tuple("multiTenancyCallActivity", null), + tuple("userTaskProcess", TENANT_ONE), + tuple("userTaskProcess", TENANT_TWO)); + } + + @Test + public void getStatisticsCountNoAuthenticatedTenant() { + // given + identityService.setAuthentication("user", null, null); + + // when + CountResultDto actual = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual.getCount()).isEqualTo(1); + } + + @Test + public void getStatisticsCountWithAuthenticatedTenant() { + // given + identityService.setAuthentication("user", null, Collections.singletonList(TENANT_ONE)); + + // when + CountResultDto actual = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual.getCount()).isEqualTo(2); + } + + @Test + public void getStatisticsCountWithDisabledTenantCheck() { + // given + processEngineConfiguration.setTenantCheckEnabled(false); + identityService.setAuthentication("user", null, null); + + // when + CountResultDto actual = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual.getCount()).isEqualTo(3); + } + + @Test + public void getStatisticsCountWithCamundaAdmin() { + // given + identityService.setAuthentication("user", Collections.singletonList(Groups.CAMUNDA_ADMIN), null); + + // when + CountResultDto actual = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual.getCount()).isEqualTo(3); + } + + @Test + public void getStatisticsCountWithAdminGroups() { + // given + identityService.setAuthentication("user", Collections.singletonList(ADMIN_GROUP), null); + + // when + CountResultDto actual = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual.getCount()).isEqualTo(3); + } + + @Test + public void getStatisticsCountWithAdminUsers() { + // given + identityService.setAuthentication("adminUser", null, null); + + // when + CountResultDto actual = resource.getStatisticsCount(uriInfo); + + // then + assertThat(actual.getCount()).isEqualTo(3); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/ProcessInstanceResourceTenantCheckTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/ProcessInstanceResourceTenantCheckTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5d6d0e16414af854579f4c012d3b69cd093559cc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/ProcessInstanceResourceTenantCheckTest.java @@ -0,0 +1,161 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base.tenantcheck; + +import static org.assertj.core.api.Assertions.assertThat; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.CalledProcessInstanceDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.query.CalledProcessInstanceQueryDto; +import org.camunda.bpm.cockpit.impl.plugin.base.sub.resources.ProcessInstanceResource; +import org.camunda.bpm.cockpit.plugin.test.AbstractCockpitPluginTest; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.authorization.Groups; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ProcessInstanceResourceTenantCheckTest extends AbstractCockpitPluginTest { + + protected static final String TENANT_ONE = "tenant1"; + protected static final String TENANT_TWO = "tenant2"; + protected static final String ADMIN_GROUP = "adminGroup"; + protected static final String ADMIN_USER = "adminUser"; + + private ProcessInstanceResource resource; + private ProcessEngine processEngine; + private ProcessEngineConfigurationImpl processEngineConfiguration; + private RuntimeService runtimeService; + private IdentityService identityService; + private CalledProcessInstanceQueryDto queryParameter; + + @Before + public void init() throws Exception { + + processEngine = getProcessEngine(); + processEngineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration(); + runtimeService = processEngine.getRuntimeService(); + identityService = processEngine.getIdentityService(); + + processEngineConfiguration.getAdminGroups().add(ADMIN_GROUP); + processEngineConfiguration.getAdminUsers().add(ADMIN_USER); + + deploy("processes/multi-tenancy-call-activity.bpmn"); + deployForTenant(TENANT_ONE, "processes/user-task-process.bpmn"); + deployForTenant(TENANT_TWO, "processes/user-task-process.bpmn"); + + ProcessInstance processInstance = runtimeService.createProcessInstanceByKey("multiTenancyCallActivity").execute(); + + resource = new ProcessInstanceResource(getProcessEngine().getName(), processInstance.getId()); + + queryParameter = new CalledProcessInstanceQueryDto(); + } + + @After + public void tearDown() { + processEngineConfiguration.getAdminGroups().remove(ADMIN_GROUP); + processEngineConfiguration.getAdminUsers().remove(ADMIN_USER); + } + + @Test + public void getCalledProcessInstancesByParentProcessInstanceIdNoAuthenticatedTenants() { + + identityService.setAuthentication("user", null, null); + + List result = resource.queryCalledProcessInstances(queryParameter); + assertThat(result).isEmpty(); + } + + @Test + public void getCalledProcessInstancesByParentProcessInstanceIdWithAuthenticatedTenant() { + + identityService.setAuthentication("user", null, Arrays.asList(TENANT_ONE)); + + List result = resource.queryCalledProcessInstances(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + CalledProcessInstanceDto dto = result.get(0); + assertThat(dto.getCallActivityId()).isEqualTo("CallActivity_Tenant1"); + } + + @Test + public void getCalledProcessInstancesByParentProcessInstanceIdDisabledTenantCheck() { + + processEngineConfiguration.setTenantCheckEnabled(false); + identityService.setAuthentication("user", null, null); + + List result = resource.queryCalledProcessInstances(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + assertThat(getCalledActivityIds(result)).contains("CallActivity_Tenant1", "CallActivity_Tenant2"); + } + + @Test + public void getCalledProcessInstancesByParentProcessInstanceIdWithCamundaAdmin() { + + identityService.setAuthentication("user", Collections.singletonList(Groups.CAMUNDA_ADMIN), null); + + List result = resource.queryCalledProcessInstances(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + assertThat(getCalledActivityIds(result)).contains("CallActivity_Tenant1", "CallActivity_Tenant2"); + } + + @Test + public void getCalledProcessInstancesByParentProcessInstanceIdWithAdminGroups() { + + identityService.setAuthentication("user", Collections.singletonList(ADMIN_GROUP), null); + + List result = resource.queryCalledProcessInstances(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + assertThat(getCalledActivityIds(result)).contains("CallActivity_Tenant1", "CallActivity_Tenant2"); + } + + @Test + public void getCalledProcessInstancesByParentProcessInstanceIdWithAdminUsers() { + + identityService.setAuthentication("adminUser", null, null); + + List result = resource.queryCalledProcessInstances(queryParameter); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + assertThat(getCalledActivityIds(result)).contains("CallActivity_Tenant1", "CallActivity_Tenant2"); + } + + private Set getCalledActivityIds(List result) { + Set callActivityIds = new HashSet<>(); + for (CalledProcessInstanceDto calledProcessInstanceDto : result) { + callActivityIds.add(calledProcessInstanceDto.getCallActivityId()); + } + return callActivityIds; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/ProcessInstanceRestServiceTenantCheckTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/ProcessInstanceRestServiceTenantCheckTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f5570e1479f9d0b3b8dee4e09126f7214869bc83 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/cockpit/plugin/base/tenantcheck/ProcessInstanceRestServiceTenantCheckTest.java @@ -0,0 +1,232 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.cockpit.plugin.base.tenantcheck; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.camunda.bpm.cockpit.impl.plugin.base.dto.IncidentStatisticsDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.ProcessInstanceDto; +import org.camunda.bpm.cockpit.impl.plugin.base.dto.query.ProcessInstanceQueryDto; +import org.camunda.bpm.cockpit.impl.plugin.resources.ProcessInstanceRestService; +import org.camunda.bpm.cockpit.plugin.test.AbstractCockpitPluginTest; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.authorization.Groups; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ProcessInstanceRestServiceTenantCheckTest extends AbstractCockpitPluginTest { + + protected static final String TENANT_ONE = "tenant1"; + protected static final String TENANT_TWO = "tenant2"; + protected static final String ADMIN_GROUP = "adminGroup"; + protected static final String ADMIN_USER = "adminUser"; + + private ProcessEngine processEngine; + private ProcessEngineConfigurationImpl processEngineConfiguration; + private RuntimeService runtimeService; + private IdentityService identityService; + + private ProcessInstanceRestService resource; + private ProcessInstanceQueryDto queryParameter; + + @Before + public void init() throws Exception { + + processEngine = getProcessEngine(); + processEngineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration(); + + runtimeService = processEngine.getRuntimeService(); + identityService = processEngine.getIdentityService(); + + processEngineConfiguration.getAdminGroups().add(ADMIN_GROUP); + processEngineConfiguration.getAdminUsers().add(ADMIN_USER); + + resource = new ProcessInstanceRestService(processEngine.getName()); + + deployForTenant(TENANT_ONE, "processes/failing-process.bpmn"); + deployForTenant(TENANT_TWO, "processes/failing-process.bpmn"); + + startProcessInstancesWithTenantId("FailingProcess", TENANT_ONE); + startProcessInstancesWithTenantId("FailingProcess", TENANT_TWO); + + queryParameter = new ProcessInstanceQueryDto(); + queryParameter.setActivityIdIn(new String[] { "ServiceTask_1" }); + } + + @After + public void tearDown() { + processEngineConfiguration.getAdminGroups().remove(ADMIN_GROUP); + processEngineConfiguration.getAdminUsers().remove(ADMIN_USER); + } + + @Test + public void queryCountNoAuthenticatedTenants() { + + identityService.setAuthentication("user", null, null); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + assertThat(result).isNotNull(); + assertThat(result.getCount()).isEqualTo(0); + } + + @Test + public void queryCountWithAuthenticatedTenant() { + + identityService.setAuthentication("user", null, Arrays.asList(TENANT_ONE)); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + assertThat(result).isNotNull(); + assertThat(result.getCount()).isEqualTo(1); + } + + @Test + public void queryCountDisabledTenantCheck() { + + processEngineConfiguration.setTenantCheckEnabled(false); + identityService.setAuthentication("user", null, null); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + assertThat(result).isNotNull(); + assertThat(result.getCount()).isEqualTo(2); + } + + @Test + public void queryCountWithCamundaAdmin() { + + identityService.setAuthentication("user", Collections.singletonList(Groups.CAMUNDA_ADMIN), null); + + CountResultDto result = resource.queryProcessInstancesCount(queryParameter); + assertThat(result).isNotNull(); + assertThat(result.getCount()).isEqualTo(2); + } + + @Test + public void queryWithContainingIncidentsNoAuthenticatedTenants() { + + identityService.setAuthentication("user", null, null); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isEmpty(); + } + + @Test + public void queryWithContainingIncidentsWithAuthenticatedTenant() { + + identityService.setAuthentication("user", null, Arrays.asList(TENANT_ONE)); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(1); + + List incidents = result.get(0).getIncidents(); + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(1); + } + + @Test + public void queryWithContainingIncidentsDisabledTenantCheck() { + + processEngineConfiguration.setTenantCheckEnabled(false); + identityService.setAuthentication("user", null, null); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + List incidents = result.get(0).getIncidents(); + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(1); + + incidents = result.get(1).getIncidents(); + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(1); + } + + @Test + public void queryWithContainingIncidentsWithCamundaAdmin() { + + identityService.setAuthentication("user", Collections.singletonList(Groups.CAMUNDA_ADMIN), null); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + List incidents = result.get(0).getIncidents(); + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(1); + + incidents = result.get(1).getIncidents(); + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(1); + } + + @Test + public void queryWithContainingIncidentsWithAdminGroups() { + + identityService.setAuthentication("user", Collections.singletonList(ADMIN_GROUP), null); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + List incidents = result.get(0).getIncidents(); + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(1); + + incidents = result.get(1).getIncidents(); + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(1); + } + + @Test + public void queryWithContainingIncidentsWithAdminUsers() { + + identityService.setAuthentication("adminUser", null, null); + + List result = resource.queryProcessInstances(queryParameter, null, null); + assertThat(result).isNotEmpty(); + assertThat(result).hasSize(2); + + List incidents = result.get(0).getIncidents(); + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(1); + + incidents = result.get(1).getIncidents(); + assertThat(incidents).isNotEmpty(); + assertThat(incidents).hasSize(1); + } + + private void startProcessInstancesWithTenantId(String processDefinitionKey, String tenantId) { + + runtimeService + .createProcessInstanceByKey(processDefinitionKey) + .processDefinitionTenantId(tenantId) + .execute(); + + executeAvailableJobs(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/db/QuerySessionFactoryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/db/QuerySessionFactoryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..10c68b714f43a6d238515248db76c3a1ef8f3957 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/db/QuerySessionFactoryTest.java @@ -0,0 +1,59 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.db; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collections; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +public class QuerySessionFactoryTest { + + @Rule + public ProcessEngineRule processEngineRule = new ProcessEngineRule("camunda-skip-check.cfg.xml"); + + private ProcessEngineConfigurationImpl processEngineConfiguration; + + @Before + public void setUp() throws Exception { + processEngineConfiguration = processEngineRule.getProcessEngineConfiguration(); + } + + @Test + public void testQuerySessionFactoryInitializationFromEngineConfig() { + // given + QuerySessionFactory querySessionFactory = new QuerySessionFactory(); + processEngineConfiguration = processEngineRule.getProcessEngineConfiguration(); + + // when + querySessionFactory.initFromProcessEngineConfiguration(processEngineConfiguration, Collections.emptyList()); + + // then + assertThat(querySessionFactory.getWrappedConfiguration()).isEqualTo(processEngineConfiguration); + assertThat(querySessionFactory.getDatabaseType()).isEqualTo(processEngineConfiguration.getDatabaseType()); + assertThat(querySessionFactory.getDataSource()).isEqualTo(processEngineConfiguration.getDataSource()); + assertThat(querySessionFactory.getDatabaseTablePrefix()).isEqualTo(processEngineConfiguration.getDatabaseTablePrefix()); + assertThat(querySessionFactory.getSkipIsolationLevelCheck()).isTrue(); + assertThat(querySessionFactory.getHistoryLevel()).isEqualTo(processEngineConfiguration.getHistoryLevel()); + assertThat(querySessionFactory.getHistory()).isEqualTo(processEngineConfiguration.getHistory()); + + } +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/engine/EnginesFilterTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/engine/EnginesFilterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..4260b3b0861af192549d7eca8f309d6fa7dc7648 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/engine/EnginesFilterTest.java @@ -0,0 +1,142 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.engine; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + +import java.util.Collections; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.camunda.bpm.cockpit.Cockpit; +import org.camunda.bpm.cockpit.impl.DefaultCockpitRuntimeDelegate; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.spi.ProcessEngineProvider; +import org.camunda.bpm.webapp.impl.IllegalWebAppConfigurationException; +import org.junit.After; +import org.junit.Test; + +/** + * + * @author nico.rehwaldt + */ +public class EnginesFilterTest { + + @Test + public void testHTML_FILE_PATTERN() throws Exception { + + // given + Pattern pattern = ProcessEnginesFilter.APP_PREFIX_PATTERN; + + // when + Matcher matcher1 = pattern.matcher("/app/cockpit/"); + Matcher matcher2 = pattern.matcher("/app/cockpit/engine1/"); + Matcher matcher3 = pattern.matcher("/app/cockpit/engine1/something/asd.html"); + Matcher matcher4 = pattern.matcher("/app/admin/engine1/something/asd.html"); + Matcher matcher5 = pattern.matcher("/app/cockpit/index.html"); + Matcher matcher6 = pattern.matcher("/app/tasklist/spring-engine/"); + + // then + assertThat(matcher1.matches()).isTrue(); + assertThat(matcher1.group(1)).isEqualTo("cockpit"); + assertThat(matcher1.groupCount()).isEqualTo(3); + assertThat(matcher1.group(2)).isNull(); + + assertThat(matcher2.matches()).isTrue(); + assertThat(matcher2.group(1)).isEqualTo("cockpit"); + assertThat(matcher2.group(2)).isEqualTo("engine1"); + assertThat(matcher2.group(3)).isEmpty(); + + assertThat(matcher3.matches()).isTrue(); + assertThat(matcher3.group(1)).isEqualTo("cockpit"); + assertThat(matcher3.group(2)).isEqualTo("engine1"); + assertThat(matcher3.group(3)).isEqualTo("something/asd.html"); + + assertThat(matcher4.matches()).isTrue(); + assertThat(matcher4.group(1)).isEqualTo("admin"); + assertThat(matcher4.group(2)).isEqualTo("engine1"); + assertThat(matcher4.group(3)).isEqualTo("something/asd.html"); + + assertThat(matcher5.matches()).isTrue(); + assertThat(matcher5.group(1)).isEqualTo("cockpit"); + assertThat(matcher5.group(2)).isEqualTo("index.html"); + assertThat(matcher5.group(3)).isEmpty(); + + assertThat(matcher6.matches()).isTrue(); + assertThat(matcher6.group(1)).isEqualTo("tasklist"); + assertThat(matcher6.group(2)).isEqualTo("spring-engine"); + assertThat(matcher6.group(3)).isEmpty(); + } + + @Test + public void testGetDefaultProcessEngine() { + + // see https://app.camunda.com/jira/browse/CAM-2126 + + // runtime delegate returns single, non-default-named process engine engine + + Cockpit.setCockpitRuntimeDelegate(new DefaultCockpitRuntimeDelegate() { + + protected ProcessEngineProvider loadProcessEngineProvider() { + return null; + } + + public Set getProcessEngineNames() { + return Collections.singleton("foo"); + } + public ProcessEngine getDefaultProcessEngine() { + return null; + } + }); + + ProcessEnginesFilter processEnginesFilter = new ProcessEnginesFilter(); + String defaultEngineName = processEnginesFilter.getDefaultEngineName(); + assertThat(defaultEngineName).isEqualTo("foo"); + + + // now it returns 'null' + + Cockpit.setCockpitRuntimeDelegate(new DefaultCockpitRuntimeDelegate() { + + protected ProcessEngineProvider loadProcessEngineProvider() { + return null; + } + + public Set getProcessEngineNames() { + return Collections.emptySet(); + } + public ProcessEngine getDefaultProcessEngine() { + return null; + } + }); + + try { + defaultEngineName = processEnginesFilter.getDefaultEngineName(); + fail(); + } catch(IllegalWebAppConfigurationException e) { + // expected + } + + } + + @After + public void cleanup() { + Cockpit.setCockpitRuntimeDelegate(null); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/engine/WebappsDatabaseNamingConsistencyTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/engine/WebappsDatabaseNamingConsistencyTest.java new file mode 100644 index 0000000000000000000000000000000000000000..24a7055de90d0053232bbaf78ae98c101c55ba59 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/engine/WebappsDatabaseNamingConsistencyTest.java @@ -0,0 +1,76 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.engine; + +import static org.assertj.core.api.Assertions.fail; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; +import org.junit.Test; + +public class WebappsDatabaseNamingConsistencyTest { + + public static String COLUMN_NAME_REGEX = "([a-zA-Z_]*(?=[a-z]+)[a-zA-Z_]+_)[,\\s]"; + public static String[] SCANNED_FOLDERS = { "org/camunda/bpm/cockpit/plugin/base/queries", + "org/camunda/bpm/admin/plugin/base/queries" }; + + @Test + public void shouldNotFindLowercaseDbColumnNamesInMappings() { + // given the rule that all DB column names are created in uppercase + + // when scanning all mapping files for lowercase column names + StringBuilder errorMessageBuilder = new StringBuilder(); + Pattern pattern = Pattern.compile(COLUMN_NAME_REGEX); + try { + for (String scannedFolder : SCANNED_FOLDERS) { + URL resource = getClass().getClassLoader().getResource(scannedFolder); + if (resource == null) { + throw new IOException("Could not find path: " + scannedFolder); + } + File folder = new File(resource.getFile()); + File[] filesInFolder = folder.listFiles(); + for (File file : filesInFolder) { + AtomicInteger lineNumber = new AtomicInteger(0); + try (Stream lines = Files.lines(file.toPath())) { + lines.forEach(line -> { + lineNumber.getAndIncrement(); + Matcher matcher = pattern.matcher(line); + while (matcher.find()) { + errorMessageBuilder.append( + "Found illegal lowercase column name " + matcher.group(1) + " in SQL " + file + " at line " + + lineNumber + ". All SQL column names should be uppercase.\n"); + } + }); + } + } + } + } catch (IOException e) { + fail("Unable to find test resource for test " + getClass().getName() + "\n" + e.getMessage()); + } + // then don't expect any results + String errorMessage = errorMessageBuilder.toString(); + if (!errorMessage.isEmpty()) { + fail(errorMessage); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/auth/AuthCacheTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/auth/AuthCacheTest.java new file mode 100644 index 0000000000000000000000000000000000000000..2526b4fa7d64b86155a2ea39bd1932e6cc5ca461 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/auth/AuthCacheTest.java @@ -0,0 +1,540 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.security.auth; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.impl.util.ClockUtil; +import org.camunda.bpm.webapp.impl.IllegalWebAppConfigurationException; +import org.camunda.bpm.webapp.impl.security.SecurityActions; +import org.camunda.bpm.webapp.impl.util.ProcessEngineUtil; +import org.camunda.bpm.webapp.impl.util.ServletContextUtil; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.MockedStatic; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockFilterConfig; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpSession; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.addDays; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +public class AuthCacheTest { + + protected MockedStatic mockedAuthenticationUtil; + + protected MockedStatic mockedSecurityActions; + + protected MockedStatic mockedProcessEngineUtil; + + @Before + public void setup() { + ClockUtil.setCurrentTime(ClockUtil.getCurrentTime()); + } + + @After + public void reset() { + Authentications.clearCurrent(); + ClockUtil.reset(); + if (mockedAuthenticationUtil != null) { + mockedAuthenticationUtil.close(); + } + if (mockedSecurityActions != null) { + mockedSecurityActions.close(); + } + if (mockedProcessEngineUtil != null) { + mockedProcessEngineUtil.close(); + } + } + + @Test + public void shouldThrowExceptionWhenTimeToLiveIsNegative() { + AuthenticationFilter authenticationFilter = new AuthenticationFilter(); + MockFilterConfig config = new MockFilterConfig(); + config.addInitParameter(AuthenticationFilter.AUTH_CACHE_TTL_INIT_PARAM_NAME, "-1000"); + assertThatThrownBy(() -> authenticationFilter.init(config)) + .isInstanceOf(IllegalWebAppConfigurationException.class) + .hasMessage("'cacheTimeToLive' cannot be negative."); + } + + @Test + public void shouldThrowExceptionSinceTimeToLiveIsNotALong() { + AuthenticationFilter authenticationFilter = new AuthenticationFilter(); + MockFilterConfig config = new MockFilterConfig(); + config.addInitParameter(AuthenticationFilter.AUTH_CACHE_TTL_INIT_PARAM_NAME, "6.7"); + assertThatThrownBy(() -> authenticationFilter.init(config)) + .isInstanceOf(NumberFormatException.class) + .hasMessage("For input string: \"6.7\""); + } + + @Test + public void shouldTrimTimeToLive() throws ServletException { + AuthenticationFilter authenticationFilter = new AuthenticationFilter(); + MockFilterConfig config = new MockFilterConfig(); + config.addInitParameter(AuthenticationFilter.AUTH_CACHE_TTL_INIT_PARAM_NAME, " 123 "); + authenticationFilter.init(config); + assertThat(authenticationFilter.getCacheTimeToLive()).isEqualTo(123); + } + + @Test + public void shouldRevalidateWhenValidationTimeDue() throws ServletException, IOException { + // given + setupEngineMock(); + AuthenticationFilter filter = setupFilter(1000 * 60 * 5); + Authentications authentications = setupAuth(); + UserAuthentication initialAuthentication = getAuthByEngine(authentications, "engine1"); + + // assume + assertThat(initialAuthentication.getCacheValidationTime()).isNull(); + + applyFilter(filter, new MockHttpServletRequest()); + + UserAuthentication nextAuth = getAuthByEngine(authentications, "engine1"); + assertThat(nextAuth.getCacheValidationTime()) + .isEqualTo(addMinutes(5, ClockUtil.getCurrentTime())); + + assertThat(initialAuthentication).isNotSameAs(nextAuth); + + Date currentTime = addDays(ClockUtil.getCurrentTime(), 2); + ClockUtil.setCurrentTime(currentTime); + + // when + applyFilter(filter, new MockHttpServletRequest()); + + // then + assertThat(getAuthByEngine(authentications, "engine1").getCacheValidationTime()) + .isEqualTo(addMinutes(5, ClockUtil.getCurrentTime())); + assertThat(initialAuthentication).isNotSameAs(getAuthByEngine(authentications, "engine1")); + } + + @Test + public void shouldRevalidateWhenTTLZero() throws ServletException, IOException { + // given + setupEngineMock(); + AuthenticationFilter filter = setupFilter(0); + Authentications authentications = setupAuth(); + UserAuthentication initialAuthentication = getAuthByEngine(authentications, "engine1"); + + // assume + assertThat(initialAuthentication.getCacheValidationTime()).isNull(); + + applyFilter(filter, new MockHttpServletRequest()); + + UserAuthentication nextAuth = getAuthByEngine(authentications, "engine1"); + assertThat(nextAuth.getCacheValidationTime()).isNull(); + + assertThat(initialAuthentication).isNotSameAs(nextAuth); + + Date currentTime = addDays(ClockUtil.getCurrentTime(), 2); + ClockUtil.setCurrentTime(currentTime); + + // when + applyFilter(filter, new MockHttpServletRequest()); + + // then + assertThat(getAuthByEngine(authentications, "engine1").getCacheValidationTime()).isNull(); + assertThat(initialAuthentication).isNotSameAs(getAuthByEngine(authentications, "engine1")); + } + + @Test + public void shouldNotRevalidateWhenValidationTimeNotDue() throws ServletException, IOException { + // given + setupEngineMock(); + AuthenticationFilter filter = setupFilter(1000 * 60 * 5); + Authentications authentications = setupAuth(); + UserAuthentication initialAuthentication = getAuthByEngine(authentications, "engine1"); + + MockHttpServletRequest request = new MockHttpServletRequest(); + + // assume + assertThat(initialAuthentication.getCacheValidationTime()).isNull(); + + applyFilter(filter, request); + + Date datePlus5Minutes = addMinutes(5, ClockUtil.getCurrentTime()); + + UserAuthentication nextAuth = getAuthByEngine(authentications, "engine1"); + assertThat(nextAuth.getCacheValidationTime()).isEqualTo(datePlus5Minutes); + assertThat(initialAuthentication).isNotSameAs(nextAuth); + + // when + applyFilter(filter, request); + + // then + assertThat(getAuthByEngine(authentications, "engine1").getCacheValidationTime()) + .isEqualTo(datePlus5Minutes); + assertThat(nextAuth).isSameAs(getAuthByEngine(authentications, "engine1")); + } + + @Test + public void shouldNotRevalidateWhenDisabled() throws ServletException, IOException { + setupEngineMock(); + Authentications authentications = setupAuth(); + UserAuthentication initialAuthentication = getAuthByEngine(authentications, "engine1"); + + MockHttpServletRequest request = new MockHttpServletRequest(); + + // assume + assertThat(initialAuthentication.getCacheValidationTime()).isNull(); + + // when + applyFilter(setupFilter(new MockFilterConfig()), request); + + // then + assertThat(initialAuthentication.getCacheValidationTime()).isNull(); + assertThat(initialAuthentication).isSameAs(getAuthByEngine(authentications, "engine1")); + } + + @Test + public void shouldSetValidationTimeInitially() throws ServletException, IOException { + // given + setupEngineMock(); + Authentications authentications = setupAuth(); + UserAuthentication initialAuthentication = getAuthByEngine(authentications, "engine1"); + + MockHttpServletRequest request = new MockHttpServletRequest(); + + // assume + assertThat(initialAuthentication.getCacheValidationTime()).isNull(); + + // when + applyFilter(setupFilter(1000 * 60 * 5), request); + + // then + UserAuthentication nextAuth = getAuthByEngine(authentications, "engine1"); + assertThat(nextAuth.getCacheValidationTime()) + .isEqualTo(addMinutes(5, ClockUtil.getCurrentTime())); + assertThat(initialAuthentication).isNotSameAs(nextAuth); + } + + @Test + public void shouldHaveValidationTimeInitially() throws ServletException, IOException { + // given + setupEngineMock(); + Authentications authentications = setupAuth(); + UserAuthentication initialAuthentication = getAuthByEngine(authentications, "engine1"); + + MockHttpServletRequest request = new MockHttpServletRequest(); + + // assume + assertThat(ServletContextUtil.getAuthCacheValidationTime(request.getServletContext())).isNull(); + + // when + applyFilter(setupFilter(1000 * 60 * 5), request); + + // then + assertThat(ServletContextUtil.getAuthCacheValidationTime(request.getServletContext())).isNotNull(); + UserAuthentication nextAuth = getAuthByEngine(authentications, "engine1"); + assertThat(nextAuth.getCacheValidationTime()) + .isEqualTo(addMinutes(5, ClockUtil.getCurrentTime())); + assertThat(initialAuthentication).isNotSameAs(nextAuth); + } + + @Test + public void shouldInvalidateSessionDueToDeletedUser() throws ServletException, IOException { + // given + ProcessEngine engineMock = setupEngineMock()[0]; + Authentications authentications = setupAuth(); + UserAuthentication initialAuthentication = getAuthByEngine(authentications, "engine1"); + AuthenticationFilter filter = setupFilter(1000 * 60 * 5); + + MockHttpServletRequest request = new MockHttpServletRequest(); + + // assume + assertThat(initialAuthentication.getCacheValidationTime()).isNull(); + + applyFilter(filter, request); + + UserAuthentication nextAuth = getAuthByEngine(authentications, "engine1"); + assertThat(nextAuth.getCacheValidationTime()).isEqualTo(addMinutes(5, ClockUtil.getCurrentTime())); + assertThat(initialAuthentication).isNotSameAs(nextAuth); + + User user = engineMock.getIdentityService() + .createUserQuery() + .userId("userId1") + .singleResult(); + + when(user).thenReturn(null); + + Date currentTime = addDays(ClockUtil.getCurrentTime(), 2); + ClockUtil.setCurrentTime(currentTime); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + // when + applyFilter(filter, request, response); + + // then + assertThat(getAuthByEngine(authentications, "engine1")).isNull(); + } + + @Test + public void shouldRevalidateWhenValidationTimeDueWithMultipleAuths() throws ServletException, IOException { + // given + setupEngineMock("engine1", "engine2", "engine3"); + AuthenticationFilter filter = setupFilter(1000 * 60 * 5); + Authentications authentications = setupAuth("engine1", "engine2", "engine3"); + + UserAuthentication authEngineOne = getAuthByEngine(authentications, "engine1"); + UserAuthentication authEngineTwo = getAuthByEngine(authentications, "engine2"); + UserAuthentication authEngineThree = getAuthByEngine(authentications, "engine3"); + + MockHttpServletRequest request = new MockHttpServletRequest(); + + // assume + assertThat(authEngineOne.getCacheValidationTime()).isNull(); + assertThat(authEngineTwo.getCacheValidationTime()).isNull(); + assertThat(authEngineThree.getCacheValidationTime()).isNull(); + + applyFilter(filter, request); + + UserAuthentication nextAuthEngineOne = getAuthByEngine(authentications, "engine1"); + assertThat(authEngineOne).isNotSameAs(nextAuthEngineOne); + UserAuthentication nextAuthEngineTwo = getAuthByEngine(authentications, "engine2"); + assertThat(authEngineTwo).isNotSameAs(nextAuthEngineTwo); + UserAuthentication nextAuthEngineThree = getAuthByEngine(authentications, "engine3"); + assertThat(authEngineThree).isNotSameAs(nextAuthEngineThree); + + Date datePlus5Minutes = addMinutes(5, ClockUtil.getCurrentTime()); + assertThat(nextAuthEngineOne.getCacheValidationTime()).isEqualTo(datePlus5Minutes); + assertThat(nextAuthEngineTwo.getCacheValidationTime()).isEqualTo(datePlus5Minutes); + assertThat(nextAuthEngineThree.getCacheValidationTime()).isEqualTo(datePlus5Minutes); + + Date currentTime = addDays(ClockUtil.getCurrentTime(), 2); + ClockUtil.setCurrentTime(currentTime); + + request = new MockHttpServletRequest(); + + // when + applyFilter(filter, request); + + // then + assertThat(authEngineOne) + .isNotSameAs(nextAuthEngineOne) + .isNotSameAs(getAuthByEngine(authentications, "engine1")); + assertThat(authEngineTwo) + .isNotSameAs(nextAuthEngineTwo) + .isNotSameAs(getAuthByEngine(authentications, "engine2")); + assertThat(authEngineThree) + .isNotSameAs(nextAuthEngineThree) + .isNotSameAs(getAuthByEngine(authentications, "engine3")); + + assertThat(getAuthByEngine(authentications, "engine1").getCacheValidationTime()) + .isEqualTo(addMinutes(5, ClockUtil.getCurrentTime())); + assertThat(getAuthByEngine(authentications, "engine2").getCacheValidationTime()) + .isEqualTo(addMinutes(5, ClockUtil.getCurrentTime())); + assertThat(getAuthByEngine(authentications, "engine3").getCacheValidationTime()) + .isEqualTo(addMinutes(5, ClockUtil.getCurrentTime())); + } + + @Test + public void shouldInvalidateSessionDueToDeletedUserWithMultipleAuths() throws ServletException, IOException { + // given + ProcessEngine[] engineMocks = setupEngineMock("engine1", "engine2", "engine3"); + Authentications authentications = setupAuth("engine1", "engine2", "engine3"); + AuthenticationFilter filter = setupFilter(1000 * 60 * 5); + + UserAuthentication authEngineOne = getAuthByEngine(authentications, "engine1"); + UserAuthentication authEngineTwo = getAuthByEngine(authentications, "engine2"); + UserAuthentication authEngineThree = getAuthByEngine(authentications, "engine3"); + + MockHttpServletRequest request = new MockHttpServletRequest(); + + // assume + assertThat(authEngineOne.getCacheValidationTime()).isNull(); + assertThat(authEngineTwo.getCacheValidationTime()).isNull(); + assertThat(authEngineThree.getCacheValidationTime()).isNull(); + + applyFilter(filter, request); + + UserAuthentication nextAuthEngineOne = getAuthByEngine(authentications, "engine1"); + assertThat(authEngineOne).isNotSameAs(nextAuthEngineOne); + UserAuthentication nextAuthEngineTwo = getAuthByEngine(authentications, "engine2"); + assertThat(authEngineTwo).isNotSameAs(nextAuthEngineTwo); + UserAuthentication nextAuthEngineThree = getAuthByEngine(authentications, "engine3"); + assertThat(authEngineThree).isNotSameAs(nextAuthEngineThree); + + Date datePlus5Minutes = addMinutes(5, ClockUtil.getCurrentTime()); + assertThat(nextAuthEngineOne.getCacheValidationTime()) + .isEqualTo(datePlus5Minutes); + assertThat(nextAuthEngineTwo.getCacheValidationTime()) + .isEqualTo(datePlus5Minutes); + assertThat(nextAuthEngineThree.getCacheValidationTime()) + .isEqualTo(datePlus5Minutes); + + User user = engineMocks[1].getIdentityService() + .createUserQuery() + .userId("userId2") + .singleResult(); + + when(user).thenReturn(null); + + Date currentTime = addDays(ClockUtil.getCurrentTime(), 2); + ClockUtil.setCurrentTime(currentTime); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + // when + applyFilter(filter, request, response); + + // then + assertThat(getAuthByEngine(authentications, "engine1")).isNotNull(); + assertThat(getAuthByEngine(authentications, "engine2")).isNull(); + assertThat(getAuthByEngine(authentications, "engine3")).isNotNull(); + } + + @Test + public void shouldNotRevalidateWhenValidationTimeNotDueWithMultipleAuths() throws ServletException, IOException { + // given + setupEngineMock("engine1", "engine2", "engine3"); + AuthenticationFilter filter = setupFilter(1000 * 60 * 5); + Authentications authentications = setupAuth("engine1", "engine2", "engine3"); + + UserAuthentication authEngineOne = getAuthByEngine(authentications, "engine1"); + UserAuthentication authEngineTwo = getAuthByEngine(authentications, "engine2"); + UserAuthentication authEngineThree = getAuthByEngine(authentications, "engine3"); + + MockHttpServletRequest request = new MockHttpServletRequest(); + + // assume + assertThat(authEngineOne.getCacheValidationTime()).isNull(); + assertThat(authEngineTwo.getCacheValidationTime()).isNull(); + assertThat(authEngineThree.getCacheValidationTime()).isNull(); + + applyFilter(filter, request); + + UserAuthentication nextAuthEngineOne = getAuthByEngine(authentications, "engine1"); + assertThat(authEngineOne).isNotSameAs(nextAuthEngineOne); + UserAuthentication nextAuthEngineTwo = getAuthByEngine(authentications, "engine2"); + assertThat(authEngineTwo).isNotSameAs(nextAuthEngineTwo); + UserAuthentication nextAuthEngineThree = getAuthByEngine(authentications, "engine3"); + assertThat(authEngineThree).isNotSameAs(nextAuthEngineThree); + + Date datePlus5Minutes = addMinutes(5, ClockUtil.getCurrentTime()); + assertThat(nextAuthEngineOne.getCacheValidationTime()).isEqualTo(datePlus5Minutes); + assertThat(nextAuthEngineTwo.getCacheValidationTime()).isEqualTo(datePlus5Minutes); + assertThat(nextAuthEngineThree.getCacheValidationTime()).isEqualTo(datePlus5Minutes); + + // when + applyFilter(filter, request); + + // then + assertThat(nextAuthEngineOne) + .isSameAs(getAuthByEngine(authentications, "engine1")); + assertThat(nextAuthEngineTwo) + .isSameAs(getAuthByEngine(authentications, "engine2")); + assertThat(nextAuthEngineThree) + .isSameAs(getAuthByEngine(authentications, "engine3")); + assertThat(getAuthByEngine(authentications, "engine1").getCacheValidationTime()).isEqualTo(datePlus5Minutes); + assertThat(getAuthByEngine(authentications, "engine1").getCacheValidationTime()).isEqualTo(datePlus5Minutes); + assertThat(getAuthByEngine(authentications, "engine1").getCacheValidationTime()).isEqualTo(datePlus5Minutes); + } + + // helpers /////////////////////////////////////////////////////////////////////////////////////////////////////////// + + protected ProcessEngine[] setupEngineMock(String... engines) { + if (engines.length == 0) engines = new String[]{"engine1"}; + + mockedAuthenticationUtil = mockStatic(AuthenticationUtil.class); + mockedProcessEngineUtil = mockStatic(ProcessEngineUtil.class); + List processEngines = new ArrayList<>(); + Arrays.asList(engines).forEach(engine -> { + ProcessEngine processEngineMock = mock(ProcessEngine.class, RETURNS_DEEP_STUBS); + processEngines.add(processEngineMock); + + when(processEngineMock.getName()).thenReturn(engine); + mockedProcessEngineUtil.when(() -> ProcessEngineUtil.lookupProcessEngine(eq(engine))).thenReturn(processEngineMock); + mockedAuthenticationUtil.when(() -> AuthenticationUtil.updateCache(any(), any(), anyLong())).thenCallRealMethod(); + mockedAuthenticationUtil.when(() -> AuthenticationUtil.getSessionMutex(any())).thenCallRealMethod(); + mockedAuthenticationUtil.when(() -> AuthenticationUtil.createAuthentication(eq(engine), any())).thenCallRealMethod(); + mockedAuthenticationUtil.when(() -> AuthenticationUtil.createAuthentication(eq(engine), any(), any(), any())).thenCallRealMethod(); + mockedAuthenticationUtil.when(() -> AuthenticationUtil.createAuthentication(eq(processEngineMock), any(), any(), any())).thenCallRealMethod(); + }); + return processEngines.toArray(new ProcessEngine[0]); + } + + protected Authentications setupAuth(String... engines) { + if (engines.length == 0) engines = new String[]{"engine1"}; + + Authentications authentications = new Authentications(); + List enginesAsList = Arrays.asList(engines); + for (int i = 0; i < enginesAsList.size(); i++) { + String engine = enginesAsList.get(i); + UserAuthentication userAuthentication = AuthenticationUtil.createAuthentication(engine, "userId" + (i + 1)); + authentications.addOrReplace(userAuthentication); + } + mockedAuthenticationUtil.when(() -> AuthenticationUtil.getAuthsFromSession(any(HttpSession.class))).thenReturn(authentications); + return authentications; + } + + protected AuthenticationFilter setupFilter(long cacheTTL) throws ServletException { + MockFilterConfig config = new MockFilterConfig(); + config.addInitParameter(AuthenticationFilter.AUTH_CACHE_TTL_INIT_PARAM_NAME, String.valueOf(cacheTTL)); + return setupFilter(config); + } + + protected AuthenticationFilter setupFilter(MockFilterConfig config) throws ServletException { + mockedSecurityActions = mockStatic(SecurityActions.class); + AuthenticationFilter authenticationFilter = new AuthenticationFilter(); + authenticationFilter.init(config); + return authenticationFilter; + } + + protected void applyFilter(AuthenticationFilter filter, MockHttpServletRequest request) throws ServletException, IOException { + applyFilter(filter, request, null); + } + + protected void applyFilter(AuthenticationFilter filter, MockHttpServletRequest request, MockHttpServletResponse response) throws ServletException, IOException { + if (response == null) { + response = new MockHttpServletResponse(); + } + + filter.doFilter(request, response, new MockFilterChain()); + } + + protected UserAuthentication getAuthByEngine(Authentications authentications, String engineName) { + return authentications.getAuthentications() + .stream() + .filter(UserAuthentication -> UserAuthentication.getProcessEngineName().equals(engineName)) + .findFirst() + .orElse(null); + } + + protected Date addMinutes(int minutes, Date currentTime) { + return new Date(currentTime.getTime() + 1000L * 60L * minutes); + } + +} + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/auth/ContainerAuthenticationFilterTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/auth/ContainerAuthenticationFilterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..c9c4909376aef6be74b1c956b7a951bf38c5d6fb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/auth/ContainerAuthenticationFilterTest.java @@ -0,0 +1,279 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.security.auth; + +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyBoolean; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.security.Principal; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.GroupQuery; +import org.camunda.bpm.engine.identity.Tenant; +import org.camunda.bpm.engine.identity.TenantQuery; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.impl.AuthorizationServiceImpl; +import org.camunda.bpm.engine.impl.IdentityServiceImpl; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.security.auth.ProcessEngineAuthenticationFilter; +import org.camunda.bpm.engine.rest.security.auth.impl.ContainerBasedAuthenticationProvider; +import org.camunda.bpm.engine.rest.spi.ProcessEngineProvider; +import org.camunda.bpm.engine.rest.spi.impl.MockedProcessEngineProvider; +import org.camunda.bpm.webapp.impl.util.ProcessEngineUtil; +import org.camunda.bpm.webapp.impl.util.ServletContextUtil; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; +import org.mockito.MockedStatic; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockFilterConfig; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockServletContext; + +@RunWith(Parameterized.class) +public class ContainerAuthenticationFilterTest { + + protected static final String SERVICE_PATH = "/camunda"; + + private Authentications authentications; + + protected AuthorizationService authorizationService; + protected IdentityService identityService; + + protected Filter authenticationFilter; + + protected String requestUrl; + protected String engineName; + protected boolean alreadyAuthenticated; + protected boolean authenticationExpected; + + protected ProcessEngine currentEngine; + + private MockedStatic authenticationUtilMockedStatic; + private MockedStatic processEngineUtilMockedStatic; + + public ContainerAuthenticationFilterTest(String requestUrl, String engineName, boolean alreadyAuthenticated, boolean authenticationExpected) { + this.requestUrl = requestUrl; + this.engineName = engineName; + if (engineName == null) { + this.engineName = "default"; + } + this.alreadyAuthenticated = alreadyAuthenticated; + this.authenticationExpected = authenticationExpected; + } + + @Parameters + public static Collection getRequestUrls() { + return Arrays.asList(new Object[][]{ + {"/app/cockpit/default/", "default", false, true}, + {"/app/cockpit/engine2/", "engine2", false, true}, + {"/api/cockpit/plugin/some-plugin/default/process-instance", "default", false, true}, + {"/api/cockpit/plugin/some-plugin/static/process-instance", null, false, false}, + + {"/app/cockpit/default/", "default", true, false}, + {"/app/cockpit/engine2/", "engine2", true, false}, + {"/api/cockpit/plugin/some-plugin/default/process-instance", "default", true, false}, + {"/api/cockpit/plugin/some-plugin/static/process-instance", null, true, false}, + + {"/app/tasklist/default/", "default", false, true}, + {"/app/tasklist/engine2/", "engine2", false, true}, + {"/api/tasklist/plugin/some-plugin/default/process-instance", "default", false, true}, + {"/api/tasklist/plugin/some-plugin/static/process-instance", null, false, false}, + + {"/app/tasklist/default/", "default", true, false}, + {"/app/tasklist/engine2/", "engine2", true, false}, + {"/api/tasklist/plugin/some-plugin/default/process-instance", "default", true, false}, + {"/api/tasklist/plugin/some-plugin/static/process-instance", null, true, false}, + + {"/app/admin/default/", "default", false, true}, + {"/app/admin/engine2/", "engine2", false, true}, + {"/api/admin/plugin/some-plugin/default/process-instance", "default", false, true}, + {"/api/admin/plugin/some-plugin/static/process-instance", null, false, false}, + + {"/app/admin/default/", "default", true, false}, + {"/app/admin/engine2/", "engine2", true, false}, + {"/api/admin/plugin/some-plugin/default/process-instance", "default", true, false}, + {"/api/admin/plugin/some-plugin/static/process-instance", null, true, false}, + + {"/app/welcome/default/", "default", false, true}, + {"/app/welcome/engine2/", "engine2", false, true}, + {"/api/welcome/plugin/some-plugin/default/process-instance", "default", false, true}, + {"/api/welcome/plugin/some-plugin/static/process-instance", null, false, false}, + + {"/api/engine/engine/default/process-instance", "default", false, true}, + {"/api/engine/engine/engine2/process-instance", "engine2", false, true}, + + {"/api/engine/engine/default/process-instance", "default", true, false}, + {"/api/engine/engine/engine2/process-instance", "engine2", true, false}, + + {"/lib/deps.js", null, false, false}, + {"/app/cockpit/styles/styles.css", null, false, false}, + {"/api/admin/auth/user/default", null, false, false}, + + {"/lib/deps.js", null, true, false}, + {"/app/cockpit/styles/styles.css", null, true, false}, + {"/api/admin/auth/user/default", null, true, false} + }); + } + + @Before + public void setup() throws ServletException { + setupProcessEngine(); + setupAuthentications(); + setupFilter(); + } + + protected void setupProcessEngine() { + final ProcessEngineProvider provider = new MockedProcessEngineProvider(); + currentEngine = provider.getProcessEngine(engineName); + + authorizationService = mock(AuthorizationServiceImpl.class); + identityService = mock(IdentityServiceImpl.class); + + when(currentEngine.getAuthorizationService()).thenReturn(authorizationService); + when(currentEngine.getIdentityService()).thenReturn(identityService); + processEngineUtilMockedStatic = mockStatic(ProcessEngineUtil.class); + processEngineUtilMockedStatic.when(() -> ProcessEngineUtil.lookupProcessEngine(any())).thenReturn(currentEngine); + + User mockedUser = mock(User.class); + when(mockedUser.getId()).thenReturn(MockProvider.EXAMPLE_USER_ID); + + UserQuery mockUserQuery = mock(UserQuery.class); + when(identityService.createUserQuery()).thenReturn(mockUserQuery); + when(mockUserQuery.userId(any())).thenReturn(mockUserQuery); + when(mockUserQuery.singleResult()).thenReturn(mockedUser); + + GroupQuery mockGroupQuery = mock(GroupQuery.class); + when(identityService.createGroupQuery()).thenReturn(mockGroupQuery); + when(mockGroupQuery.groupMember(any())).thenReturn(mockGroupQuery); + when(mockGroupQuery.list()).thenReturn(new ArrayList()); + + TenantQuery mockTenantQuery = mock(TenantQuery.class); + when(identityService.createTenantQuery()).thenReturn(mockTenantQuery); + when(mockTenantQuery.userMember(any())).thenReturn(mockTenantQuery); + when(mockTenantQuery.includingGroupsOfUser(anyBoolean())).thenReturn(mockTenantQuery); + when(mockTenantQuery.list()).thenReturn(new ArrayList()); + } + + protected void setupAuthentications() { + Authentications.clearCurrent(); + authenticationUtilMockedStatic = mockStatic(AuthenticationUtil.class); + authentications = mock(Authentications.class); + authenticationUtilMockedStatic.when(() -> AuthenticationUtil.getAuthsFromSession(any())).thenReturn(authentications); + UserAuthentication authentication = mock(UserAuthentication.class); + authenticationUtilMockedStatic + .when(() -> AuthenticationUtil.createAuthentication(any(ProcessEngine.class), any(), any(), any())) + .thenReturn(authentication); + } + + protected void setupFilter() throws ServletException { + MockFilterConfig config = new MockFilterConfig(); + config.addInitParameter(ProcessEngineAuthenticationFilter.AUTHENTICATION_PROVIDER_PARAM, ContainerBasedAuthenticationProvider.class.getName()); + authenticationFilter = new ContainerBasedAuthenticationFilter(); + authenticationFilter.init(config); + } + + protected void applyFilter(MockHttpServletRequest request, MockHttpServletResponse response, String username) throws IOException, ServletException { + Principal principal = mock(Principal.class); + when(principal.getName()).thenReturn(username); + request.setUserPrincipal(principal); + request.setMethod("GET"); + FilterChain filterChain = new MockFilterChain(); + authenticationFilter.doFilter(request, response, filterChain); + } + + @After + public void teardown() { + authenticationUtilMockedStatic.close(); + processEngineUtilMockedStatic.close(); + } + + @Test + public void shouldCheckCustomApplicationPath() throws IOException, ServletException { + testContainerAuthenticationCheck("/my-custom/application/path"); + } + + @Test + public void shouldCheckEmptyApplicationPath() throws IOException, ServletException { + testContainerAuthenticationCheck(""); + } + + public void testContainerAuthenticationCheck(String applicationPath) throws IOException, ServletException { + if (alreadyAuthenticated) { + Authentication authentication = mock(Authentication.class); + when(authentication.getProcessEngineName()).thenReturn(engineName); + when(authentication.getIdentityId()).thenReturn(MockProvider.EXAMPLE_USER_ID); + + when(authentications.getAuthenticationForProcessEngine(anyString())).thenReturn(authentication); + } + else { + when(authentications.getAuthenticationForProcessEngine(anyString())).thenReturn(null); + } + + MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletRequest request = null; + + if (!applicationPath.isEmpty()) { + MockServletContext mockServletContext = new MockServletContext(); + request = new MockHttpServletRequest(mockServletContext); + requestUrl = applicationPath + requestUrl; + ServletContextUtil.setAppPath(applicationPath, mockServletContext); + + } else { + request = new MockHttpServletRequest(); + + } + + request.setRequestURI(SERVICE_PATH + requestUrl); + request.setContextPath(SERVICE_PATH); + applyFilter(request, response, MockProvider.EXAMPLE_USER_ID); + + Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); + + if (authenticationExpected) { + verify(authentications).addOrReplace(any(UserAuthentication.class)); + + } else { + verify(authentications, never()).addOrReplace(any(UserAuthentication.class)); + } + } +} + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/auth/UserAuthenticationResourceLoggingTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/auth/UserAuthenticationResourceLoggingTest.java new file mode 100644 index 0000000000000000000000000000000000000000..af503280b997fe2ac0e7addd417cb798cba4cbf7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/auth/UserAuthenticationResourceLoggingTest.java @@ -0,0 +1,303 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.security.auth; + +import static org.assertj.core.api.Assertions.assertThat; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import java.util.List; +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.authorization.Authorization; +import org.camunda.bpm.engine.authorization.Permissions; +import org.camunda.bpm.engine.authorization.Resources; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.util.ClockUtil; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.commons.testing.ProcessEngineLoggingRule; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; + +public class UserAuthenticationResourceLoggingTest { + + @Rule + public ProcessEngineRule processEngineRule = new ProcessEngineRule("camunda-test-engine.cfg.xml"); + @Rule + public ProcessEngineLoggingRule loggingRule = new ProcessEngineLoggingRule().watch("org.camunda.bpm.webapp") + .level(Level.INFO); + + protected ProcessEngine processEngine; + protected ProcessEngineConfigurationImpl processEngineConfiguration; + protected IdentityService identityService; + protected AuthorizationService authorizationService; + + protected boolean authorizationEnabledInitialValue; + protected boolean webappsAuthenticationLoggingEnabledInitialValue; + + @Before + public void setUp() { + this.processEngine = processEngineRule.getProcessEngine(); + this.processEngineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration(); + this.identityService = processEngine.getIdentityService(); + this.authorizationService = processEngine.getAuthorizationService(); + + authorizationEnabledInitialValue = processEngineConfiguration.isAuthorizationEnabled(); + webappsAuthenticationLoggingEnabledInitialValue = processEngineConfiguration.isWebappsAuthenticationLoggingEnabled(); + } + + @After + public void tearDown() { + ClockUtil.reset(); + processEngineConfiguration.setAuthorizationEnabled(authorizationEnabledInitialValue); + processEngineConfiguration.setWebappsAuthenticationLoggingEnabled(webappsAuthenticationLoggingEnabledInitialValue); + + for (User user : identityService.createUserQuery().list()) { + identityService.deleteUser(user.getId()); + } + for (Authorization authorization : authorizationService.createAuthorizationQuery().list()) { + authorizationService.deleteAuthorization(authorization.getId()); + } + + Authentications.clearCurrent(); + } + + @Test + public void shouldProduceLogStatementOnValidLogin() { + // given + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + + processEngineConfiguration.setWebappsAuthenticationLoggingEnabled(true); + + // when + authResource.doLogin("webapps-test-engine", "tasklist", "jonny", "jonnyspassword"); + + // then + List filteredLog = loggingRule.getFilteredLog("jonny"); + assertThat(filteredLog).hasSize(1); + assertThat(filteredLog.get(0).getFormattedMessage()).contains("Successful login for user jonny"); + } + + @Test + public void shouldNotProduceLogStatementOnValidLoginWhenDisabled() { + // given + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + + processEngineConfiguration.setWebappsAuthenticationLoggingEnabled(false); + + // when + authResource.doLogin("webapps-test-engine", "tasklist", "jonny", "jonnyspassword"); + + // then + List filteredLog = loggingRule.getFilteredLog("jonny"); + assertThat(filteredLog).hasSize(0); + } + + @Test + public void shouldProduceLogStatementOnInvalidLogin() { + // given + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + + processEngineConfiguration.setWebappsAuthenticationLoggingEnabled(true); + + // when + authResource.doLogin("webapps-test-engine", "tasklist", "jonny", "NOT_jonnyspassword"); + + // then + List filteredLog = loggingRule.getFilteredLog("jonny"); + assertThat(filteredLog).hasSize(1); + assertThat(filteredLog.get(0).getFormattedMessage()).contains("Failed login attempt for user jonny. Reason: bad credentials"); + } + + @Test + public void shouldNotProduceLogStatementOnInvalidLoginWhenDisabled() { + // given + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + + processEngineConfiguration.setWebappsAuthenticationLoggingEnabled(false); + + // when + authResource.doLogin("webapps-test-engine", "tasklist", "jonny", "NOT_jonnyspassword"); + + // then + List filteredLog = loggingRule.getFilteredLog("jonny"); + assertThat(filteredLog).hasSize(0); + } + + @Test + public void shouldProduceLogStatementOnLogout() { + // given + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + setAuthentication("jonny", "webapps-test-engine"); + + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + + processEngineConfiguration.setWebappsAuthenticationLoggingEnabled(true); + + // when + authResource.doLogout("webapps-test-engine"); + + // then + List filteredLog = loggingRule.getFilteredLog("jonny"); + assertThat(filteredLog).hasSize(1); + assertThat(filteredLog.get(0).getFormattedMessage()).contains("Successful logout for user jonny"); + } + + @Test + public void shouldNotProduceLogStatementOnLogoutWhenDisabled() { + // given + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + setAuthentication("jonny", "webapps-test-engine"); + + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + + processEngineConfiguration.setWebappsAuthenticationLoggingEnabled(false); + + // when + authResource.doLogout("webapps-test-engine"); + + // then + List filteredLog = loggingRule.getFilteredLog("jonny"); + assertThat(filteredLog).hasSize(0); + } + + @Test + public void shouldNotProduceLogStatementOnLogoutWhenNoAuthentication() { + // given + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + + processEngineConfiguration.setWebappsAuthenticationLoggingEnabled(true); + + // when + authResource.doLogout("webapps-test-engine"); + + // then + List filteredLog = loggingRule.getFilteredLog("jonny"); + assertThat(filteredLog).hasSize(0); + } + + @Test + public void shouldProduceLogStatementOnLoginWhenAuthorized() { + // given + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + + Authorization authorization = authorizationService.createNewAuthorization(Authorization.AUTH_TYPE_GRANT); + authorization.setResource(Resources.APPLICATION); + authorization.setResourceId("tasklist"); + authorization.setPermissions(new Permissions[] {Permissions.ACCESS}); + authorization.setUserId(jonny.getId()); + authorizationService.saveAuthorization(authorization); + + processEngineConfiguration.setAuthorizationEnabled(true); + processEngineConfiguration.setWebappsAuthenticationLoggingEnabled(true); + + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + + // when + authResource.doLogin("webapps-test-engine", "tasklist", "jonny", "jonnyspassword"); + + // then + List filteredLog = loggingRule.getFilteredLog("jonny"); + assertThat(filteredLog).hasSize(1); + assertThat(filteredLog.get(0).getFormattedMessage()).contains("Successful login for user jonny"); + } + + @Test + public void shouldProduceLogStatementOnLoginWhenNotAuthorized() { + // given + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + + processEngineConfiguration.setAuthorizationEnabled(true); + processEngineConfiguration.setWebappsAuthenticationLoggingEnabled(true); + + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + + // when + authResource.doLogin("webapps-test-engine", "tasklist", "jonny", "jonnyspassword"); + + // then + List filteredLog = loggingRule.getFilteredLog("jonny"); + assertThat(filteredLog).hasSize(1); + assertThat(filteredLog.get(0).getFormattedMessage()).contains("Failed login attempt for user jonny. Reason: not authorized"); + } + + @Test + public void shouldNotProduceLogStatementOnLoginWhenNotAuthorizedAndWebappsLoggingDisabled() { + // given + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + + processEngineConfiguration.setAuthorizationEnabled(true); + processEngineConfiguration.setWebappsAuthenticationLoggingEnabled(false); + + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + + // when + authResource.doLogin("webapps-test-engine", "tasklist", "jonny", "jonnyspassword"); + + // then + List filteredLog = loggingRule.getFilteredLog("jonny"); + assertThat(filteredLog).hasSize(0); + } + + protected void setAuthentication(String user, String engineName) { + Authentications authentications = new Authentications(); + authentications.addOrReplace(new UserAuthentication(user, engineName)); + Authentications.setCurrent(authentications); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/auth/UserAuthenticationResourceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/auth/UserAuthenticationResourceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..1116db08823de79af4b6e24812e6e949e3cedd09 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/auth/UserAuthenticationResourceTest.java @@ -0,0 +1,238 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.security.auth; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mockStatic; + +import java.util.Date; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.authorization.Authorization; +import org.camunda.bpm.engine.authorization.Permissions; +import org.camunda.bpm.engine.authorization.Resources; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.impl.util.ClockUtil; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.webapp.impl.util.ServletContextUtil; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.MockedStatic; +import org.springframework.mock.web.MockHttpServletRequest; + +/** + * @author Thorben Lindhauer + * + */ +public class UserAuthenticationResourceTest { + + @Rule + public ProcessEngineRule processEngineRule = new ProcessEngineRule("camunda-test-engine.cfg.xml"); + + protected ProcessEngine processEngine; + protected ProcessEngineConfiguration processEngineConfiguration; + protected IdentityService identityService; + protected AuthorizationService authorizationService; + + @Before + public void setUp() { + this.processEngine = processEngineRule.getProcessEngine(); + this.processEngineConfiguration = processEngine.getProcessEngineConfiguration(); + this.identityService = processEngine.getIdentityService(); + this.authorizationService = processEngine.getAuthorizationService(); + } + + @After + public void tearDown() { + ClockUtil.reset(); + processEngineConfiguration.setAuthorizationEnabled(false); + + for (User user : identityService.createUserQuery().list()) { + identityService.deleteUser(user.getId()); + } + for (Authorization authorization : authorizationService.createAuthorizationQuery().list()) { + authorizationService.deleteAuthorization(authorization.getId()); + } + + clearAuthentication(); + } + + @Test + public void testAuthorizationCheckGranted() { + // given + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + + Authorization authorization = authorizationService.createNewAuthorization(Authorization.AUTH_TYPE_GRANT); + authorization.setResource(Resources.APPLICATION); + authorization.setResourceId("tasklist"); + authorization.setPermissions(new Permissions[] {Permissions.ACCESS}); + authorization.setUserId(jonny.getId()); + authorizationService.saveAuthorization(authorization); + + processEngineConfiguration.setAuthorizationEnabled(true); + setAuthentication("jonny", "webapps-test-engine"); + + // when + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + Response response = authResource.doLogin("webapps-test-engine", "tasklist", "jonny", "jonnyspassword"); + + // then + Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); + } + + @Test + public void testSessionRevalidationOnAuthorization() { + // given + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + + Authorization authorization = authorizationService.createNewAuthorization(Authorization.AUTH_TYPE_GRANT); + authorization.setResource(Resources.APPLICATION); + authorization.setResourceId("tasklist"); + authorization.setPermissions(new Permissions[] {Permissions.ACCESS}); + authorization.setUserId(jonny.getId()); + authorizationService.saveAuthorization(authorization); + + processEngineConfiguration.setAuthorizationEnabled(true); + setAuthentication("jonny", "webapps-test-engine"); + + // when + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + String oldSessionId = authResource.request.getSession().getId(); + + // first login session + Response response = authResource.doLogin("webapps-test-engine", "tasklist", "jonny", "jonnyspassword"); + String newSessionId = authResource.request.getSession().getId(); + + authResource.doLogout("webapps-test-engine"); + + // second login session + response = authResource.doLogin("webapps-test-engine", "tasklist", "jonny", "jonnyspassword"); + String newestSessionId = authResource.request.getSession().getId(); + + // then + Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); + Assert.assertNotEquals(oldSessionId, newSessionId); + Assert.assertNotEquals(newSessionId, newestSessionId); + } + + @Test + public void testAuthorizationCheckNotGranted() { + // given + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + + processEngineConfiguration.setAuthorizationEnabled(true); + setAuthentication("jonny", "webapps-test-engine"); + + // when + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + Response response = authResource.doLogin("webapps-test-engine", "tasklist", "jonny", "jonnyspassword"); + + // then + Assert.assertEquals(Status.FORBIDDEN.getStatusCode(), response.getStatus()); + } + + @Test + public void testAuthorizationCheckDeactivated() { + // given + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + + processEngineConfiguration.setAuthorizationEnabled(false); + setAuthentication("jonny", "webapps-test-engine"); + + // when + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + Response response = authResource.doLogin("webapps-test-engine", "tasklist", "jonny", "jonnyspassword"); + + // then + Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); + } + + @Test + public void shouldSetAuthCacheValidationTime() { + // given + ClockUtil.setCurrentTime(ClockUtil.getCurrentTime()); + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + + MockHttpServletRequest request = new MockHttpServletRequest(); + ServletContextUtil.setCacheTTLForLogin(1000 * 60 * 5, request.getServletContext()); + + // when + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = request; + authResource.doLogin("webapps-test-engine", "tasklist", "jonny", "jonnyspassword"); + + // then + UserAuthentication userAuthentication = AuthenticationUtil.getAuthsFromSession(request.getSession()) + .getAuthentications() + .get(0); + assertThat(userAuthentication.getCacheValidationTime()) + .isEqualTo(new Date(ClockUtil.getCurrentTime().getTime() + 1000 * 60 * 5)); + } + + @Test + public void shouldReturnUnauthorizedOnNullAuthentication() { + // given + User jonny = identityService.newUser("jonny"); + jonny.setPassword("jonnyspassword"); + identityService.saveUser(jonny); + UserAuthenticationResource authResource = new UserAuthenticationResource(); + authResource.request = new MockHttpServletRequest(); + + try (MockedStatic authenticationUtilMock = mockStatic(AuthenticationUtil.class)) { + authenticationUtilMock.when(() -> AuthenticationUtil.createAuthentication("webapps-test-engine", "jonny")).thenReturn(null); + + // when + Response response = authResource.doLogin("webapps-test-engine", "tasklist", "jonny", "jonnyspassword"); + + // then + Assert.assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus()); + } + } + + protected void setAuthentication(String user, String engineName) { + Authentications authentications = new Authentications(); + authentications.addOrReplace(new UserAuthentication(user, engineName)); + Authentications.setCurrent(authentications); + } + + protected void clearAuthentication() { + Authentications.clearCurrent(); + } + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/RequestFilterTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/RequestFilterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d14c7c0ffa9eab76e83ce5e402a1b7b8debd6012 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/RequestFilterTest.java @@ -0,0 +1,126 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.security.filter; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Map; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +/** + * + * @author nico.rehwaldt + */ +@RunWith(Parameterized.class) +public class RequestFilterTest { + + protected static final String EMPTY_PATH = ""; + protected static final String CUSTOM_APP_PATH = "/my-custom/application/path"; + + private RequestFilter matcher; + + private Map matchResult; + + protected String applicationPath; + + @Parameterized.Parameters + public static Collection data() { + return Arrays.asList(EMPTY_PATH, CUSTOM_APP_PATH); + } + + public RequestFilterTest(String applicationPath) { + this.applicationPath = applicationPath; + } + + @Test + public void shouldMatchMethod() { + + // given + matcher = newMatcher("/foo/bar", "POST", "PUT"); + + // when + matchResult = matcher.match("GET", applicationPath + "/foo/bar"); + + // then + assertThat(matchResult).isNull(); + } + + @Test + public void shouldNotMatchUri() { + + // given + matcher = newMatcher("/foo/bar", "GET"); + + // when + matchResult = matcher.match("GET", applicationPath + "/not-matching/"); + + // then + assertThat(matchResult).isNull(); + } + + @Test + public void shouldMatch() { + + // given + matcher = newMatcher("/foo/bar", "GET"); + + // when + matchResult = matcher.match("GET", applicationPath + "/foo/bar"); + + // then + assertThat(matchResult).isNotNull(); + } + + @Test + public void shouldExtractNamedUriParts() { + + // given + matcher = newMatcher("/{foo}/{bar}", "GET"); + + // when + matchResult = matcher.match("GET", applicationPath + "/foo/bar"); + + // then + assertThat(matchResult) + .isNotNull() + .containsEntry("foo", "foo") + .containsEntry("bar", "bar"); + } + + @Test + public void shouldExtractNamedMatchAllUriPart() { + + // given + matcher = newMatcher("/{foo}/{bar:.*}", "GET"); + + // when + matchResult = matcher.match("GET", applicationPath + "/foo/bar/asdf/asd"); + + // then + assertThat(matchResult) + .isNotNull() + .containsEntry("bar", "bar/asdf/asd"); + } + + private RequestFilter newMatcher(String uri, String ... methods) { + return new RequestFilter(uri, applicationPath, methods); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/SecurityFilterRulesTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/SecurityFilterRulesTest.java new file mode 100644 index 0000000000000000000000000000000000000000..baebeee31d35987a137c85308d9b5092609db06b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/SecurityFilterRulesTest.java @@ -0,0 +1,536 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.security.filter; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; + +import org.camunda.bpm.cockpit.Cockpit; +import org.camunda.bpm.cockpit.impl.DefaultCockpitRuntimeDelegate; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.webapp.impl.security.auth.Authentication; +import org.camunda.bpm.webapp.impl.security.auth.Authentications; +import org.camunda.bpm.webapp.impl.security.auth.UserAuthentication; +import org.camunda.bpm.webapp.impl.security.filter.util.FilterRules; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.mockito.Mockito; + +/** + * + * @author nico.rehwaldt + */ +@RunWith(Parameterized.class) +public class SecurityFilterRulesTest { + + public static final String FILTER_RULES_FILE = "src/main/webapp/WEB-INF/securityFilterRules.json"; + + protected static final String EMPTY_PATH = ""; + protected static final String CUSTOM_APP_PATH = "/my-custom/application/path"; + + public static List FILTER_RULES; + + public static Authentication NO_AUTHENTICATION = null; + public static Authentication LOGGED_IN_USER = new Authentication("user", "default"); + + public static final String TESTUSER_ID = "testuser"; + + protected String applicationPath; + + @Parameterized.Parameters + public static Collection data() { + return Arrays.asList(EMPTY_PATH, CUSTOM_APP_PATH); + } + + public SecurityFilterRulesTest(String applicationPath) throws IOException { + this.applicationPath = applicationPath; + FILTER_RULES = loadFilterRules(applicationPath); + } + + @Before + public void createEngine() + { + final ProcessEngine engine = Mockito.mock(ProcessEngine.class); + + Cockpit.setCockpitRuntimeDelegate(new DefaultCockpitRuntimeDelegate() { + + @Override + public ProcessEngine getProcessEngine(String processEngineName) { + if ("default".equals(processEngineName)) { + return engine; + } + else { + return null; + } + } + }); + } + + @After + public void after() { + Authentications.setCurrent(null); + Cockpit.setCockpitRuntimeDelegate(null); + } + + @Test + public void shouldHaveRulesLoaded() throws Exception { + assertThat(FILTER_RULES).hasSize(1); + } + + + @Test + public void shouldPassPasswordPolicy() { + assertThat(isAuthorized("GET", + applicationPath + "/api/engine/engine/default/identity/password-policy")).isTrue(); + assertThat(isAuthorized("POST", + applicationPath + "/api/engine/engine/default/identity/password-policy")).isTrue(); + } + + @Test + public void shouldPassStaticCockpitPluginResources_GET() throws Exception { + assertThat(isAuthorized("GET", + applicationPath + "/api/cockpit/plugin/some-plugin/static/foo.html")).isTrue(); + assertThat(isAuthorized("GET", + applicationPath + "/api/cockpit/plugin/bar/static/foo.html")).isTrue(); + } + + @Test + public void shouldRejectEngineApi_GET() throws Exception { + + authenticatedForEngine("otherEngine", new Runnable() { + @Override + public void run() { + + Authorization authorization = + getAuthorization("POST", applicationPath + "/api/engine/engine/default/bar"); + + assertThat(authorization.isGranted()).isFalse(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + }); + } + + @Test + public void shouldGrantEngineApi_GET() throws Exception { + + authenticatedForEngine("default", new Runnable() { + @Override + public void run() { + + Authorization authorization = + getAuthorization("POST", applicationPath + "/api/engine/engine/default/bar"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isTrue(); + } + }); + } + + @Test + public void shouldRejectCockpitPluginApi_GET() throws Exception { + + authenticatedForEngine("otherEngine", new Runnable() { + @Override + public void run() { + + Authorization authorization = getAuthorization("POST", + applicationPath + "/api/cockpit/plugin/" + + "reporting-process-count/default/process-instance-count"); + + assertThat(authorization.isGranted()).isFalse(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + }); + } + + @Test + public void shouldPassCockpitPluginApi_GET_LOGGED_IN() throws Exception { + authenticatedForEngine("default", new Runnable() { + @Override + public void run() { + + Authorization authorization = + getAuthorization("POST", + applicationPath + "/api/cockpit/plugin/" + + "reporting-process-count/default/process-instance-count"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isTrue(); + } + }); + } + + @Test + public void shouldPassCockpit_GET_LOGGED_OUT() throws Exception { + + Authorization authorization = + getAuthorization("GET", applicationPath + "/app/cockpit/non-existing-engine/foo"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + + @Test + public void shouldPassCockpit_GET_LOGGED_IN() throws Exception { + + authenticatedForApp("default", "cockpit", new Runnable() { + + @Override + public void run() { + Authorization authorization = + getAuthorization("GET", applicationPath + "/app/cockpit/default/"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isTrue(); + } + }); + } + + @Test + public void shouldPassCockpitNonExistingEngine_GET_LOGGED_IN() throws Exception { + + authenticatedForApp("default", "cockpit", new Runnable() { + + @Override + public void run() { + Authorization authorization = + getAuthorization("GET", applicationPath + "/app/cockpit/non-existing-engine/"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + }); + } + + + @Test + public void shouldRejectTasklistApi_GET() throws Exception { + + authenticatedForEngine("otherEngine", new Runnable() { + @Override + public void run() { + + Authorization authorization = + getAuthorization("POST", + applicationPath + "/api/tasklist/plugin/example-plugin/default/example-resource"); + + assertThat(authorization.isGranted()).isFalse(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + }); + } + + @Test + public void shouldPassTasklistApi_GET_LOGGED_IN() throws Exception { + authenticatedForEngine("default", new Runnable() { + @Override + public void run() { + + Authorization authorization = + getAuthorization("POST", + applicationPath + "/api/tasklist/plugin/example-plugin/default/example-resource"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isTrue(); + } + }); + } + + @Test + public void shouldRejectTasklistApi_GET_LOGGED_OUT() throws Exception + { + Authorization authorization = + getAuthorization("POST", + applicationPath + "/api/tasklist/plugin/example-plugin/default/example-resource"); + + assertThat(authorization.isGranted()).isFalse(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + + @Test + public void shouldPassTasklistPluginResource_GET_LOGGED_IN() throws Exception { + + authenticatedForEngine("default", new Runnable() { + @Override + public void run() { + + Authorization authorization = + getAuthorization("GET", + applicationPath + "/api/tasklist/plugin/example-plugin/static/example-resource"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + }); + } + + @Test + public void shouldPassTasklistPluginResource_GET_LOGGED_OUT() throws Exception { + + Authorization authorization = + getAuthorization("GET", + applicationPath + "/api/tasklist/plugin/example-plugin/static/example-resource"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + + + @Test + public void shouldPassTasklist_GET_LOGGED_OUT() throws Exception { + + Authorization authorization = + getAuthorization("GET", applicationPath + "/app/tasklist/non-existing-engine"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + + @Test + public void shouldPassTasklist_GET_LOGGED_IN() throws Exception { + + authenticatedForApp("default", "tasklist", new Runnable() { + + @Override + public void run() { + Authorization authorization = + getAuthorization("GET", applicationPath + "/app/tasklist/default/"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isTrue(); + } + }); + } + + @Test + public void shouldRejectAdminApi_GET_LOGGED_OUT() throws Exception { + + Authorization authorization = + getAuthorization("GET", applicationPath + "/api/admin/auth/user/some-engine/"); + + assertThat(authorization.isGranted()).isFalse(); + assertThat(authorization.isAuthenticated()).isFalse(); + + authorization = + getAuthorization("GET", applicationPath + "/api/admin/setup/some-engine/"); + + assertThat(authorization.isGranted()).isFalse(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + + @Test + public void shouldPassAdminApi_GET_LOGGED_IN() throws Exception { + + authenticatedForApp("default", "admin", new Runnable() { + + @Override + public void run() { + Authorization authorization = + getAuthorization("GET", applicationPath + "/api/admin/foo/"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + }); + } + + @Test + public void shouldPassAdminApi_AnonymousEndpoints_LOGGED_OUT() throws Exception { + + Authorization authorization = + getAuthorization("GET", applicationPath + "/api/admin/auth/user/bar"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + + authorization = + getAuthorization("POST", applicationPath + "/api/admin/auth/user/bar/logout"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + + authorization = + getAuthorization("POST", applicationPath + "/api/admin/auth/user/bar/login/some-app"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + + authorization = + getAuthorization("POST", applicationPath + "/api/admin/setup/some-engine/user/create"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + + + @Test + public void shouldRejectAdminApiPlugin_GET_LOGGED_OUT() throws Exception { + + Authorization authorization = + getAuthorization("GET", + applicationPath + "/api/admin/plugin/adminPlugins/some-engine/endpoint"); + + assertThat(authorization.isGranted()).isFalse(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + + @Test + public void shouldPassAdminApiPlugin_GET_LOGGED_IN() throws Exception { + + authenticatedForApp("default", "admin", new Runnable() { + + @Override + public void run() { + Authorization authorization = + getAuthorization("GET", + applicationPath + "/api/admin/plugin/adminPlugins/some-engine"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + }); + } + + @Test + public void shouldPassAdmin_GET_LOGGED_OUT() throws Exception { + + Authorization authorization = + getAuthorization("GET", applicationPath + "/app/admin/default"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + + @Test + public void shouldPassAdmin_GET_LOGGED_IN() throws Exception { + + authenticatedForApp("default", "admin", new Runnable() { + + @Override + public void run() { + Authorization authorization = + getAuthorization("GET", applicationPath + "/app/admin/default/"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isTrue(); + } + }); + } + + + @Test + public void shouldPassAdminResources_GET_LOGGED_OUT() throws Exception { + + Authorization authorization = + getAuthorization("GET", applicationPath + "/app/admin/scripts"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + + @Test + public void shouldPassAdminResources_GET_LOGGED_IN() throws Exception { + + authenticatedForApp("default", "admin", new Runnable() { + + @Override + public void run() { + Authorization authorization = + getAuthorization("GET", applicationPath + "/app/admin/scripts"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + }); + } + + @Test + public void shouldPassAdminLicenseCheck_GET_LOGGED_OUT() { + + Authorization authorization = + getAuthorization("GET", applicationPath + "/api/admin/plugin/license/default/check-key"); + + assertThat(authorization.isGranted()).isTrue(); + assertThat(authorization.isAuthenticated()).isFalse(); + } + + protected Authorization getAuthorization(String method, String uri) { + return FilterRules.authorize(method, uri, FILTER_RULES); + } + + protected boolean isAuthorized(String method, String uri) { + return getAuthorization(method, uri).isGranted(); + } + + private static List loadFilterRules(String appPath) throws IOException { + InputStream is = null; + + try { + is = new FileInputStream(FILTER_RULES_FILE); + return FilterRules.load(is, appPath); + } finally { + IoUtil.closeSilently(is); + } + } + + private void authenticatedForEngine(String engineName, Runnable codeBlock) { + UserAuthentication engineAuth = new UserAuthentication(LOGGED_IN_USER.getIdentityId(), engineName); + + Authentications authentications = new Authentications(); + authentications.addOrReplace(engineAuth); + + Authentications.setCurrent(authentications); + + try { + codeBlock.run(); + } finally { + Authentications.clearCurrent(); + } + } + + private void authenticatedForApp(String engineName, String appName, Runnable codeBlock) { + HashSet authorizedApps = new HashSet<>(Arrays.asList(appName)); + + UserAuthentication engineAuth = new UserAuthentication(LOGGED_IN_USER.getIdentityId(), engineName); + engineAuth.setGroupIds(Collections. emptyList()); + engineAuth.setTenantIds(Collections. emptyList()); + engineAuth.setAuthorizedApps(authorizedApps); + + Authentications authentications = new Authentications(); + authentications.addOrReplace(engineAuth); + + Authentications.setCurrent(authentications); + + try { + codeBlock.run(); + } finally { + Authentications.clearCurrent(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/SessionCookieTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/SessionCookieTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d4b0f6b0a1e2bbcfd0c16df737a5ea5b0db8f2b2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/SessionCookieTest.java @@ -0,0 +1,183 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.security.filter; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.webapp.impl.util.HeaderRule; +import org.junit.Rule; +import org.junit.Test; + +public class SessionCookieTest { + + @Rule + public HeaderRule headerRule = new HeaderRule(); + + @Test + public void shouldConfigureDefault() { + // given + headerRule.startServer("web.xml", "session"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches(headerRule.getSessionCookieRegex("camunda", "Lax", false)); + } + + @Test + public void shouldConfigureRootContextPath() { + // given + headerRule.startServer("web.xml", "session", "/"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches(headerRule.getSessionCookieRegex(null, "Lax", false)); + } + + @Test + public void shouldConfigureSecureEnabled() { + // given + headerRule.startServer("secure_enabled_web.xml", "session"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches(headerRule.getSessionCookieRegex("camunda", "Lax", true)); + } + + @Test + public void shouldConfigureSameSiteDisabled() { + // given + headerRule.startServer("same_site_disabled_web.xml", "session"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches(headerRule.getSessionCookieRegex("camunda", null, false)); + } + + @Test + public void shouldConfigureSameSiteOptionStrict() { + // given + headerRule.startServer("same_site_option_strict_web.xml", "session"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches(headerRule.getSessionCookieRegex("camunda", "Strict", false)); + } + + @Test + public void shouldConfigureSameSiteOptionLax() { + // given + headerRule.startServer("same_site_option_lax_web.xml", "session"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches(headerRule.getSessionCookieRegex("camunda", "Lax", false)); + } + + @Test + public void shouldConfigureSameSiteCustomValue() { + // given + headerRule.startServer("same_site_custom_value_web.xml", "session"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches(headerRule.getSessionCookieRegex("camunda", "aCustomValue", false)); + } + + @Test + public void shouldThrowExceptionWhenConfiguringBothSameSiteOptionAndValue() { + // given + headerRule.startServer("same_site_option_value_web.xml", "session"); + + // when + headerRule.performRequest(); + + Throwable expectedException = headerRule.getException(); + + // then + assertThat(expectedException) + .isInstanceOf(ProcessEngineException.class) + .hasMessage("Please either configure sameSiteCookieOption or sameSiteCookieValue."); + } + + @Test + public void shouldThrowExceptionWhenConfiguringUnknownSameSiteOption() { + // given + headerRule.startServer("same_site_option_unknown_web.xml", "session"); + + // when + headerRule.performRequest(); + + Throwable expectedException = headerRule.getException(); + + // then + assertThat(expectedException) + .isInstanceOf(ProcessEngineException.class) + .hasMessage("For sameSiteCookieOption param, please configure one of the following options: [LAX, STRICT]"); + } + + @Test + public void shouldIgnoreCaseOfParamValues() { + // given + headerRule.startServer("ignore_case_web.xml", "session"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches(headerRule.getSessionCookieRegex("camunda", "Lax", true)); + } + + @Test + public void shouldConfigureCookieName() { + // given + headerRule.startServer("changed_cookie_name_web.xml", "session"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches(headerRule.getSessionCookieRegex("camunda", "MYCOOKIENAME", "Lax", false)); + } + + @Test + public void shouldConfigureWhenCookieIsSent() { + // given + headerRule.startServer("web.xml", "session"); + + // when + headerRule.performRequestWithHeader("Cookie", "JSESSIONID=aToken"); + + // then + assertThat(headerRule.getCookieHeader()).matches(headerRule.getSessionCookieRegex("camunda", "Lax", false)); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/csrf/CsrfPreventionCookieTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/csrf/CsrfPreventionCookieTest.java new file mode 100644 index 0000000000000000000000000000000000000000..af1c6b90262b6783f8c26ef658408a19719183c3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/csrf/CsrfPreventionCookieTest.java @@ -0,0 +1,199 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.security.filter.csrf; + +import javax.servlet.http.HttpServletResponse; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.webapp.impl.util.HeaderRule; +import org.junit.Rule; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CsrfPreventionCookieTest { + + @Rule + public HeaderRule headerRule = new HeaderRule(); + + @Test + public void shouldConfigureDefault() { + // given + headerRule.startServer("web.xml", "csrf"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches("XSRF-TOKEN=[A-Z0-9]{32};Path=/camunda;SameSite=Lax"); + } + + @Test + public void shouldConfigureRootContextPath() { + // given + headerRule.startServer("web.xml", "csrf", "/"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches("XSRF-TOKEN=[A-Z0-9]{32};Path=/;SameSite=Lax"); + } + + @Test + public void shouldConfigureSecureEnabled() { + // given + headerRule.startServer("secure_enabled_web.xml", "csrf"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches("XSRF-TOKEN=[A-Z0-9]{32};Path=/camunda;SameSite=Lax;Secure"); + } + + @Test + public void shouldConfigureSameSiteDisabled() { + // given + headerRule.startServer("same_site_disabled_web.xml", "csrf"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches("XSRF-TOKEN=[A-Z0-9]{32};Path=/camunda"); + } + + @Test + public void shouldConfigureSameSiteOptionStrict() { + // given + headerRule.startServer("same_site_option_strict_web.xml", "csrf"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches("XSRF-TOKEN=[A-Z0-9]{32};Path=/camunda;SameSite=Strict"); + } + + @Test + public void shouldConfigureSameSiteOptionLax() { + // given + headerRule.startServer("same_site_option_lax_web.xml", "csrf"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches("XSRF-TOKEN=[A-Z0-9]{32};Path=/camunda;SameSite=Lax"); + } + + @Test + public void shouldConfigureSameSiteCustomValue() { + // given + headerRule.startServer("same_site_custom_value_web.xml", "csrf"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches("XSRF-TOKEN=[A-Z0-9]{32};Path=/camunda;SameSite=aCustomValue"); + } + + @Test + public void shouldThrowExceptionWhenConfiguringBothSameSiteOptionAndValue() { + // given + headerRule.startServer("same_site_option_value_web.xml", "csrf"); + + // when + headerRule.performRequest(); + + Throwable expectedException = headerRule.getException(); + + // then + assertThat(expectedException) + .isInstanceOf(ProcessEngineException.class) + .hasMessage("Please either configure sameSiteCookieOption or sameSiteCookieValue."); + } + + @Test + public void shouldThrowExceptionWhenConfiguringUnknownSameSiteOption() { + // given + headerRule.startServer("same_site_option_unknown_web.xml", "csrf"); + + // when + headerRule.performRequest(); + + Throwable expectedException = headerRule.getException(); + + // then + assertThat(expectedException) + .isInstanceOf(ProcessEngineException.class) + .hasMessage("For sameSiteCookieOption param, please configure one of the following options: [LAX, STRICT]"); + } + + @Test + public void shouldIgnoreCaseOfParamValues() { + // given + headerRule.startServer("ignore_case_web.xml", "csrf"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()).matches("XSRF-TOKEN=[A-Z0-9]{32};Path=/camunda;SameSite=Lax;Secure"); + } + + @Test + public void shouldConfigureWhenCookieIsSent() { + // given + headerRule.startServer("web.xml", "csrf"); + + // when + headerRule.performRequestWithHeader("Cookie", "XSRF-TOKEN=aToken"); + + // then + assertThat(headerRule.getCookieHeader()).matches("XSRF-TOKEN=[A-Z0-9]{32};Path=/camunda;SameSite=Lax"); + } + + @Test + public void shouldConfigureCookieName() { + // given + headerRule.startServer("changed_cookie_name_web.xml", "csrf"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getCookieHeader()) + .matches("myCookieName=[A-Z0-9]{32};Path=/camunda;SameSite=Lax"); + } + + @Test + public void shouldRejectModifyingRequest() { + // given + headerRule.startServer("web.xml", "csrf"); + + // when + headerRule.performPostRequest("/api/admin/auth/user/default/login/welcome"); + + // then + assertThat(headerRule.getResponseCode()) + .isEqualTo(HttpServletResponse.SC_FORBIDDEN); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/csrf/CsrfPreventionFilterAppPathTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/csrf/CsrfPreventionFilterAppPathTest.java new file mode 100644 index 0000000000000000000000000000000000000000..e64857b9fcfabfc0e88260c65479da23f28eec79 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/csrf/CsrfPreventionFilterAppPathTest.java @@ -0,0 +1,98 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.security.filter.csrf; + +import org.camunda.bpm.webapp.impl.util.ServletContextUtil; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.mock.web.MockServletContext; + +import javax.servlet.ServletException; +import javax.ws.rs.core.Response; +import java.io.IOException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.webapp.impl.security.filter.util.CsrfConstants.CSRF_PATH_FIELD_NAME; +import static org.camunda.bpm.webapp.impl.security.filter.util.CookieConstants.SET_COOKIE_HEADER_NAME; + +public class CsrfPreventionFilterAppPathTest extends CsrfPreventionFilterTest { + + protected static final String MY_APP_PATH = "/my/application/path"; + + protected MockServletContext mockServletContext; + + public CsrfPreventionFilterAppPathTest(String nonModifyingRequestUrl, + String modifyingRequestUrl, + boolean isModifyingFetchRequest) { + super(nonModifyingRequestUrl, modifyingRequestUrl, isModifyingFetchRequest); + } + + @Override + public void setup() throws Exception { + mockServletContext = new MockServletContext(); + ServletContextUtil.setAppPath(MY_APP_PATH, mockServletContext); + super.setup(); + } + + @Test + public void shouldCheckNonModifyingRequestTokenGenerationWithRootContextPathAndEmptyAppPath() + throws IOException, ServletException { + // given + MockServletContext mockServletContext = new MockServletContext(); + ServletContextUtil.setAppPath("", mockServletContext); + + MockHttpSession session = new MockHttpSession(); + MockHttpServletRequest nonModifyingRequest = new MockHttpServletRequest(mockServletContext); + nonModifyingRequest.setMethod("GET"); + nonModifyingRequest.setSession(session); + + // set root context path in request + nonModifyingRequest.setRequestURI("/" + nonModifyingRequestUrl); + nonModifyingRequest.setContextPath(""); + + // when + MockHttpServletResponse response = new MockHttpServletResponse(); + applyFilter(nonModifyingRequest, response); + + // then + String cookieToken = response.getHeader(SET_COOKIE_HEADER_NAME); + String headerToken = response.getHeader(CSRF_HEADER_NAME); + + assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); + + assertThat(cookieToken).isNotNull().isNotEmpty(); + assertThat(headerToken).isNotNull().isNotEmpty(); + + String regex = CSRF_COOKIE_NAME + "=[A-Z0-9]{32}" + CSRF_PATH_FIELD_NAME + "/;SameSite=Lax"; + assertThat(cookieToken).matches(regex.replace(";", ";\\s*")); + + assertThat(cookieToken).contains(headerToken); + } + + @Override + protected String getCookiePath(String contextPath) { + return super.getCookiePath(contextPath + MY_APP_PATH); + } + + @Override + protected MockHttpServletRequest getMockedRequest() { + return new MockHttpServletRequest(mockServletContext); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/csrf/CsrfPreventionFilterTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/csrf/CsrfPreventionFilterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..038a0e2586a0c031b24bd7d69b34a0d77155e18d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/csrf/CsrfPreventionFilterTest.java @@ -0,0 +1,267 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.security.filter.csrf; + +import org.camunda.bpm.webapp.impl.security.filter.CsrfPreventionFilter; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockFilterConfig; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockHttpSession; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.webapp.impl.security.filter.util.CsrfConstants.CSRF_PATH_FIELD_NAME; +import static org.camunda.bpm.webapp.impl.security.filter.util.CookieConstants.SET_COOKIE_HEADER_NAME; + +/** + * @author Nikola Koevski + */ +@RunWith(Parameterized.class) +public class CsrfPreventionFilterTest { + + protected static final String SERVICE_PATH = "/camunda"; + protected static final String CSRF_COOKIE_NAME = "XSRF-TOKEN"; + protected static final String CSRF_HEADER_NAME = "X-XSRF-TOKEN"; + protected static final String CSRF_HEADER_REQUIRED = "Required"; + + protected Filter csrfPreventionFilter; + + protected String nonModifyingRequestUrl; + protected String modifyingRequestUrl; + + // flags a modifying request (POST/PUT/DELETE) as a non-modifying one + protected boolean isModifyingFetchRequest; + + @Parameterized.Parameters + public static Collection getRequestUrls() { + return Arrays.asList(new Object[][]{ + {"/app/cockpit/default/", "/api/admin/auth/user/default/login/cockpit", true}, + {"/app/cockpit/engine1/", "/api/admin/auth/user/engine1/login/cockpit", true}, + + {"/app/cockpit/default/", "/api/engine/engine/default/history/task/count", false}, + {"/app/cockpit/engine1/", "/api/engine/engine/engine1/history/task/count", false}, + + {"/app/tasklist/default/", "/api/admin/auth/user/default/login/tasklist", true}, + {"/app/tasklist/engine1/", "/api/admin/auth/user/engine1/login/tasklist", true}, + + {"/app/tasklist/default/", "api/engine/engine/default/task/task-id/submit-form", false}, + {"/app/tasklist/engine2/", "api/engine/engine/engine2/task/task-id/submit-form", false}, + + {"/app/admin/default/", "/api/admin/auth/user/default/login/admin", true}, + {"/app/admin/engine1/", "/api/admin/auth/user/engine1/login/admin", true}, + + {"/app/admin/default/", "api/admin/setup/default/user/create", false}, + {"/app/admin/engine3/", "api/admin/setup/engine3/user/create", false}, + + {"/app/welcome/default/", "/api/admin/auth/user/default/login/welcome", true}, + {"/app/welcome/engine1/", "/api/admin/auth/user/engine1/login/welcome", true} + }); + } + + public CsrfPreventionFilterTest(String nonModifyingRequestUrl, String modifyingRequestUrl, boolean isModifyingFetchRequest) { + this.nonModifyingRequestUrl = nonModifyingRequestUrl; + this.modifyingRequestUrl = modifyingRequestUrl; + this.isModifyingFetchRequest = isModifyingFetchRequest; + } + + @Before + public void setup() throws Exception { + setupFilter(); + } + + protected void setupFilter() throws ServletException { + MockFilterConfig config = new MockFilterConfig(); + csrfPreventionFilter = new CsrfPreventionFilter(); + csrfPreventionFilter.init(config); + } + + protected void applyFilter(MockHttpServletRequest request, MockHttpServletResponse response) throws IOException, ServletException { + FilterChain filterChain = new MockFilterChain(); + csrfPreventionFilter.doFilter(request, response, filterChain); + } + + @Test + public void testNonModifyingRequestTokenGeneration() throws IOException, ServletException { + MockHttpServletResponse response = performNonModifyingRequest(nonModifyingRequestUrl, new MockHttpSession()); + + String cookieToken = (String) response.getHeader(SET_COOKIE_HEADER_NAME); + String headerToken = (String) response.getHeader(CSRF_HEADER_NAME); + + Assert.assertNotNull(cookieToken); + Assert.assertNotNull(headerToken); + + String regex = CSRF_COOKIE_NAME + "=[A-Z0-9]{32}" + CSRF_PATH_FIELD_NAME + getCookiePath(SERVICE_PATH) + ";SameSite=Lax"; + assertThat(cookieToken).matches(regex.replace(";", ";\\s*")); + + Assert.assertEquals("No HTTP Header Token!",false, headerToken.isEmpty()); + assertThat(cookieToken).contains(headerToken); + } + + @Test + public void testNonModifyingRequestTokenGenerationWithRootContextPath() throws IOException, ServletException { + // given + MockHttpSession session = new MockHttpSession(); + MockHttpServletRequest nonModifyingRequest = getMockedRequest(); + nonModifyingRequest.setMethod("GET"); + nonModifyingRequest.setSession(session); + + // set root context path in request + nonModifyingRequest.setRequestURI("/" + nonModifyingRequestUrl); + nonModifyingRequest.setContextPath(""); + + // when + MockHttpServletResponse response = new MockHttpServletResponse(); + applyFilter(nonModifyingRequest, response); + + // then + String cookieToken = (String) response.getHeader(SET_COOKIE_HEADER_NAME); + String headerToken = (String) response.getHeader(CSRF_HEADER_NAME); + + Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + Assert.assertNotNull(cookieToken); + Assert.assertNotNull(headerToken); + + String regex = CSRF_COOKIE_NAME + "=[A-Z0-9]{32}" + CSRF_PATH_FIELD_NAME + getCookiePath("") + ";SameSite=Lax"; + assertThat(cookieToken).matches(regex.replace(";", ";\\s*")); + + Assert.assertEquals("No HTTP Header Token!",false, headerToken.isEmpty()); + assertThat(cookieToken).contains(headerToken); + } + + @Test + public void testConsecutiveNonModifyingRequestTokens() throws IOException, ServletException { + MockHttpSession session = new MockHttpSession(); + + // first non-modifying request + MockHttpServletResponse firstResponse = performNonModifyingRequest(nonModifyingRequestUrl, session); + // second non-modifying request + MockHttpServletResponse secondResponse = performNonModifyingRequest(nonModifyingRequestUrl, session); + + String headerToken1 = (String) firstResponse.getHeader(CSRF_HEADER_NAME); + String headerToken2 = (String) secondResponse.getHeader(CSRF_HEADER_NAME); + + Assert.assertNotNull(headerToken1); + Assert.assertNull(headerToken2); + } + + @Test + public void testModifyingRequestTokenValidation() throws IOException, ServletException { + MockHttpSession session = new MockHttpSession(); + + // first a non-modifying request to obtain a token + MockHttpServletResponse nonModifyingResponse = performNonModifyingRequest(nonModifyingRequestUrl, session); + + if (!isModifyingFetchRequest) { + String token = (String) nonModifyingResponse.getHeader(CSRF_HEADER_NAME); + HttpServletResponse modifyingResponse = performModifyingRequest(token, session); + Assert.assertEquals(Response.Status.OK.getStatusCode(), modifyingResponse.getStatus()); + } + } + + @Test + public void testModifyingRequestInvalidToken() throws IOException, ServletException { + MockHttpSession session = new MockHttpSession(); + performNonModifyingRequest(nonModifyingRequestUrl, session); + + if (!isModifyingFetchRequest) { + // invalid header token + MockHttpServletResponse response = performModifyingRequest("invalid header token", session); + Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus()); + Assert.assertEquals("CSRFPreventionFilter: Invalid HTTP Header Token.", response.getErrorMessage()); + + // no token in header + MockHttpServletResponse response2 = new MockHttpServletResponse(); + MockHttpServletRequest modifyingRequest = getMockedRequest(); + modifyingRequest.setMethod("POST"); + modifyingRequest.setSession(session); + modifyingRequest.setRequestURI(SERVICE_PATH + modifyingRequestUrl); + modifyingRequest.setContextPath(SERVICE_PATH); + + applyFilter(modifyingRequest, response2); + Assert.assertEquals(CSRF_HEADER_REQUIRED, response2.getHeader(CSRF_HEADER_NAME)); + Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response2.getStatus()); + Assert.assertEquals("CSRFPreventionFilter: Token provided via HTTP Header is absent/empty.", response2.getErrorMessage()); + Assert.assertNotEquals(modifyingRequest.getSession().getId(), session.getId()); + } + } + + protected MockHttpServletResponse performNonModifyingRequest(String requestUrl, MockHttpSession session) throws IOException, ServletException { + MockHttpServletResponse response = new MockHttpServletResponse(); + + MockHttpServletRequest nonModifyingRequest = getMockedRequest(); + nonModifyingRequest.setMethod("GET"); + nonModifyingRequest.setSession(session); + nonModifyingRequest.setRequestURI(SERVICE_PATH + requestUrl); + nonModifyingRequest.setContextPath(SERVICE_PATH); + + applyFilter(nonModifyingRequest, response); + + Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + return response; + } + + protected MockHttpServletResponse performModifyingRequest(String token, MockHttpSession session) throws IOException, ServletException { + MockHttpServletResponse response = new MockHttpServletResponse(); + + MockHttpServletRequest modifyingRequest = getMockedRequest(); + + modifyingRequest.setMethod("POST"); + modifyingRequest.setSession(session); + modifyingRequest.setRequestURI(SERVICE_PATH + modifyingRequestUrl); + modifyingRequest.setContextPath(SERVICE_PATH); + + modifyingRequest.addHeader(CSRF_HEADER_NAME, token); + Cookie[] cookies = {new Cookie(CSRF_COOKIE_NAME, token)}; + modifyingRequest.setCookies(cookies); + + applyFilter(modifyingRequest, response); + + return response; + } + + protected MockHttpServletRequest getMockedRequest() { + return new MockHttpServletRequest(); + } + + protected String getCookiePath(String contextPath) { + if (contextPath.isEmpty()) { + return "/"; + + } else { + return contextPath; + + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/headersec/ContentSecurityPolicyTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/headersec/ContentSecurityPolicyTest.java new file mode 100644 index 0000000000000000000000000000000000000000..96797091351160a270221b2fa9f91017e1230b68 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/headersec/ContentSecurityPolicyTest.java @@ -0,0 +1,83 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.security.filter.headersec; + +import org.camunda.bpm.webapp.impl.util.HeaderRule; +import org.junit.Rule; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.webapp.impl.security.filter.headersec.provider.impl.ContentSecurityPolicyProvider.HEADER_DEFAULT_VALUE; +import static org.camunda.bpm.webapp.impl.security.filter.headersec.provider.impl.ContentSecurityPolicyProvider.HEADER_NAME; +import static org.camunda.bpm.webapp.impl.security.filter.headersec.provider.impl.ContentSecurityPolicyProvider.HEADER_NONCE_PLACEHOLDER; + +public class ContentSecurityPolicyTest { + + @Rule + public HeaderRule headerRule = new HeaderRule(); + + @Test + public void shouldConfigureEnabledByDefault() { + // given + headerRule.startServer("web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + String expectedHeaderPattern = HEADER_DEFAULT_VALUE.replace(HEADER_NONCE_PLACEHOLDER, "'nonce-([-_a-zA-Z\\d]*)'"); + assertThat(headerRule.getHeader(HEADER_NAME)).matches(expectedHeaderPattern); + } + + @Test + public void shouldConfigureDisabled() { + // given + headerRule.startServer("csp/disabled_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.headerExists(HEADER_NAME)).isFalse(); + } + + @Test + public void shouldConfigureDisabledIgnoreCase() { + // given + headerRule.startServer("csp/disabled_ignore_case_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.headerExists(HEADER_NAME)).isFalse(); + } + + @Test + public void shouldConfigureCustomValue() { + // given + headerRule.startServer("csp/custom_value_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getHeader(HEADER_NAME)) + .isEqualTo("base-uri 'self'; default-src 'self' 'unsafe-inline'; img-src 'self' data:; block-all-mixed-content"); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/headersec/ContentTypeOptionsTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/headersec/ContentTypeOptionsTest.java new file mode 100644 index 0000000000000000000000000000000000000000..a3622e58721c925b85ef418e41c78799f4297613 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/headersec/ContentTypeOptionsTest.java @@ -0,0 +1,82 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.security.filter.headersec; + +import org.camunda.bpm.webapp.impl.util.HeaderRule; +import org.junit.Rule; +import org.junit.Test; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +public class ContentTypeOptionsTest { + + public static final String HEADER_NAME = "X-Content-Type-Options"; + public static final String HEADER_DEFAULT_VALUE = "nosniff"; + + @Rule + public HeaderRule headerRule = new HeaderRule(); + + @Test + public void shouldConfigureEnabledByDefault() { + // given + headerRule.startServer("web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getHeader(HEADER_NAME), is(HEADER_DEFAULT_VALUE)); + } + + @Test + public void shouldConfigureDisabled() { + // given + headerRule.startServer("cto/disabled_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.headerExists(HEADER_NAME), is(false)); + } + + @Test + public void shouldConfigureDisabledIgnoreCase() { + // given + headerRule.startServer("cto/disabled_ignore_case_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.headerExists(HEADER_NAME), is(false)); + } + + @Test + public void shouldConfigureCustomValue() { + // given + headerRule.startServer("cto/custom_value_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getHeader(HEADER_NAME), is("aCustomValue")); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/headersec/StrictTransportSecurityTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/headersec/StrictTransportSecurityTest.java new file mode 100644 index 0000000000000000000000000000000000000000..c1131de9809eb8bd032808f2ccd501af904b1dac --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/headersec/StrictTransportSecurityTest.java @@ -0,0 +1,133 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.security.filter.headersec; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.webapp.impl.util.HeaderRule; +import org.junit.Rule; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.webapp.impl.security.filter.headersec.provider.impl.StrictTransportSecurityProvider.HEADER_NAME; + +public class StrictTransportSecurityTest { + + @Rule + public HeaderRule headerRule = new HeaderRule(); + + @Test + public void shouldConfigureDisabledByDefault() { + // given + headerRule.startServer("web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getHeader(HEADER_NAME)).isNull(); + } + + @Test + public void shouldConfigureEnabled() { + // given + headerRule.startServer("hsts/enabled_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.headerExists(HEADER_NAME)).isTrue(); + } + + @Test + public void shouldConfigureEnabledIgnoreCase() { + // given + headerRule.startServer("hsts/enabled_ignore_case_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.headerExists(HEADER_NAME)).isTrue(); + } + + @Test + public void shouldConfigureCustomValue() { + // given + headerRule.startServer("hsts/custom_value_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getHeader(HEADER_NAME)).isEqualTo("aCustomValue"); + } + + @Test + public void shouldThrowExceptionWhenConfiguringCustomValueAndMaxAge() { + // given + headerRule.startServer("hsts/max_age_and_value_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + Throwable expectedException = headerRule.getException(); + + // then + assertThat(expectedException) + .isInstanceOf(ProcessEngineException.class) + .hasMessage("StrictTransportSecurityProvider: cannot set hstsValue " + + "in conjunction with hstsMaxAge or hstsIncludeSubdomainsDisabled."); + } + + @Test + public void shouldConfigureIncludeSubdomains() { + // given + headerRule.startServer("hsts/include_subdomains_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getHeader(HEADER_NAME)).isEqualTo("max-age=31536000; includeSubDomains"); + } + + @Test + public void shouldConfigureIncludeSubdomainsAndMaxAge() { + // given + headerRule.startServer("hsts/include_subdomains_max_age_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getHeader(HEADER_NAME)).isEqualTo("max-age=47; includeSubDomains"); + } + + @Test + public void shouldConfigureMaxAge() { + // given + headerRule.startServer("hsts/max_age_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getHeader(HEADER_NAME)).isEqualTo("max-age=47"); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/headersec/XssProtectionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/headersec/XssProtectionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5ab82dbe2291ab58bc59de2698cb938f0e8f57a7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/security/filter/headersec/XssProtectionTest.java @@ -0,0 +1,150 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.security.filter.headersec; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.webapp.impl.util.HeaderRule; +import org.junit.Rule; +import org.junit.Test; + +import static org.camunda.bpm.webapp.impl.security.filter.headersec.provider.impl.XssProtectionOption.BLOCK; +import static org.camunda.bpm.webapp.impl.security.filter.headersec.provider.impl.XssProtectionOption.SANITIZE; +import static org.camunda.bpm.webapp.impl.security.filter.headersec.provider.impl.XssProtectionProvider.HEADER_NAME; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.junit.Assert.assertThat; + +/** + * @author Tassilo Weidner + */ +public class XssProtectionTest { + + @Rule + public HeaderRule headerRule = new HeaderRule(); + + @Test + public void shouldConfigureEnabledByDefault() { + // given + headerRule.startServer("web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getHeader(HEADER_NAME), is(BLOCK.getHeaderValue())); + } + + @Test + public void shouldConfigureDisabled() { + // given + headerRule.startServer("xss/disabled_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.headerExists(HEADER_NAME), is(false)); + } + + @Test + public void shouldConfigureDisabledIgnoreCase() { + // given + headerRule.startServer("xss/disabled_ignore_case_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.headerExists(HEADER_NAME), is(false)); + } + + @Test + public void shouldConfigureCustomValue() { + // given + headerRule.startServer("xss/custom_value_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getHeader(HEADER_NAME), is("aCustomValue")); + } + + @Test + public void shouldConfigureOptionSanitize() { + // given + headerRule.startServer("xss/option_sanitize_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getHeader(HEADER_NAME), is(SANITIZE.getHeaderValue())); + } + + @Test + public void shouldConfigureOptionSanitizeIgnoreCase() { + // given + headerRule.startServer("xss/option_sanitize_ignore_case_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getHeader(HEADER_NAME), is(SANITIZE.getHeaderValue())); + } + + @Test + public void shouldConfigureOptionBlock() { + // given + headerRule.startServer("xss/option_block_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + // then + assertThat(headerRule.getHeader(HEADER_NAME), is(BLOCK.getHeaderValue())); + } + + @Test + public void shouldThrowExceptionOnSetBothParamsOptionAndValue() { + // given + headerRule.startServer("xss/option_and_value_web.xml", "headersec"); + + // when + headerRule.performRequest(); + + Throwable expectedException = headerRule.getException(); + + // then + assertThat(expectedException, instanceOf(ProcessEngineException.class)); + assertThat(expectedException.getMessage(), is("XssProtectionProvider: cannot set both xssProtectionValue and xssProtectionOption.")); + } + + @Test + public void shouldThrowExceptionOnNonExistingOption() { + // given + headerRule.startServer("xss/option_non_existing_web.xml", "headersec"); + + Throwable expectedException = headerRule.getException(); + + // then + assertThat(expectedException, instanceOf(ProcessEngineException.class)); + assertThat(expectedException.getMessage(), is("XssProtectionProvider: cannot set non-existing option foo for xssProtectionOption.")); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/util/HeaderRule.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/util/HeaderRule.java new file mode 100644 index 0000000000000000000000000000000000000000..dae92c726dbb8cd8e7233bd9c699ca347b63eb85 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/impl/util/HeaderRule.java @@ -0,0 +1,184 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.impl.util; + +import java.io.IOException; +import java.net.BindException; +import java.net.HttpURLConnection; +import java.net.ProtocolException; +import java.net.URL; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.webapp.WebAppContext; +import org.junit.rules.ExternalResource; + +/** + * @author Tassilo Weidner + */ +public class HeaderRule extends ExternalResource { + + protected static final int SERVER_PORT = 8085; + protected static final int RETRIES = 3; + + protected Server server = new Server(SERVER_PORT); + protected WebAppContext webAppContext = new WebAppContext(); + protected HttpURLConnection connection = null; + + @Override + protected void before() { + try { + server.stop(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + protected void after() { + try { + server.stop(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public void startServer(String webDescriptor, String scope) { + startServer(webDescriptor, scope, "/camunda"); + } + + public void startServer(String webDescriptor, String scope, String contextPath) { + startServer(webDescriptor, scope, contextPath, RETRIES); + } + + protected void startServer(String webDescriptor, String scope, String contextPath, int startUpRetries) { + webAppContext.setContextPath(contextPath); + webAppContext.setResourceBase("/"); + webAppContext.setDescriptor("src/test/resources/WEB-INF/" + scope + "/" + webDescriptor); + + server.setHandler(webAppContext); + + try { + server.start(); + } catch (Exception e) { + if (e.getCause() instanceof BindException && startUpRetries > 0) { + try { + Thread.sleep(500L); + } catch (Exception ex) { + } + startServer(webDescriptor, scope, contextPath, --startUpRetries); + } else { + throw new RuntimeException(e); + } + } + } + + public void performRequest() { + performRequestWithHeader(null, null, "", null); + } + + public void performPostRequest(String path) { + performRequestWithHeader(null, null, path, "POST"); + } + + public void performRequestWithHeader(String name, String value) { + performRequestWithHeader(name, value, "", null); + } + + public void performRequestWithHeader(String name, String value, String path, String method) { + try { + connection = + (HttpURLConnection) new URL("http://localhost:" + SERVER_PORT + "/camunda" + path) + .openConnection(); + } catch (IOException e) { + throw new RuntimeException(e); + } + + if ("POST".equals(method)) { + try { + connection.setRequestMethod("POST"); + } catch (ProtocolException e) { + throw new RuntimeException(e); + } + } + + if (name != null && value != null) { + connection.setRequestProperty(name, value); + } + + try { + connection.connect(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public String getHeader(String headerName) { + return connection.getHeaderField(headerName); + } + + public String getCookieHeader() { + return connection.getHeaderField("Set-Cookie"); + } + + public Throwable getException() { + return webAppContext.getUnavailableException(); + } + + public boolean headerExists(String name) { + for (String key : connection.getHeaderFields().keySet()) { + if (name.equals(key)) { + return true; + } + } + + return false; + } + + public String getResponseBody() { + try { + return connection.getResponseMessage(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public int getResponseCode() { + try { + return connection.getResponseCode(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public String getSessionCookieRegex(String path, String sameSite, boolean secure) { + return getSessionCookieRegex(path, "JSESSIONID", sameSite, secure); + } + + public String getSessionCookieRegex(String path, String cookieName, String sameSite, boolean secure) { + StringBuilder regex = new StringBuilder(cookieName + "=.*;\\W*Path=/"); + if (path != null) { + regex.append(path); + } + if (sameSite != null) { + regex.append(";\\W*SameSite=").append(sameSite); + } + if (secure) { + regex.append(";\\W*Secure"); + } + return regex.toString(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/plugin/resource/AbstractAppPluginRootResourceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/plugin/resource/AbstractAppPluginRootResourceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..cc75843e374a65919bfb4df172504e8502e0ef48 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/java/org/camunda/bpm/webapp/plugin/resource/AbstractAppPluginRootResourceTest.java @@ -0,0 +1,144 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.webapp.plugin.resource; + +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.webapp.AppRuntimeDelegate; +import org.camunda.bpm.webapp.plugin.AppPluginRegistry; +import org.camunda.bpm.webapp.plugin.spi.AppPlugin; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; +import org.mockito.Mockito; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.StreamingOutput; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginRootResource.MIME_TYPE_TEXT_CSS; +import static org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginRootResource.MIME_TYPE_TEXT_JAVASCRIPT; + +@RunWith(Parameterized.class) +public class AbstractAppPluginRootResourceTest { + + public static final String PLUGIN_NAME = "test-plugin"; + public static final String ASSET_DIR = "plugin/asset-dir"; + public static final String ASSET_CONTENT = "content"; + + private final String assetName; + private final String assetMediaType; + private final boolean assetAllowed; + + private AppRuntimeDelegate runtimeDelegate; + private AppPluginRegistry pluginRegistry; + private AbstractAppPluginRootResource pluginRootResource; + private ServletContext mockServletContext; + + public AbstractAppPluginRootResourceTest(String assetName, String assetMediaType, boolean assetAllowed) { + this.assetName = assetName; + this.assetMediaType = assetMediaType; + this.assetAllowed = assetAllowed; + } + + @Parameters + public static Collection getAssets() { + return Arrays.asList(new Object[][]{ + {"app/plugin.js", MIME_TYPE_TEXT_JAVASCRIPT, true}, + {"app/plugin.css", MIME_TYPE_TEXT_CSS, true}, + {"app/asset.js", MIME_TYPE_TEXT_JAVASCRIPT, true}, + {null, null, false}, + {"", null, false}, + {"app/plugin.cs", null, false}, + {"../..", null, false}, + {"../../annotations-api.jar", null, false}, + }); + } + + @Before + public void setup() throws ServletException { + runtimeDelegate = Mockito.mock(AppRuntimeDelegate.class); + pluginRegistry = Mockito.mock(AppPluginRegistry.class); + AppPlugin plugin = Mockito.mock(AppPlugin.class); + + Mockito.doReturn(pluginRegistry).when(runtimeDelegate).getAppPluginRegistry(); + Mockito.doReturn(plugin).when(pluginRegistry).getPlugin(PLUGIN_NAME); + Mockito.doReturn(ASSET_DIR).when(plugin).getAssetDirectory(); + + pluginRootResource = new AbstractAppPluginRootResource<>(PLUGIN_NAME, runtimeDelegate); + mockServletContext = Mockito.mock(ServletContext.class); + pluginRootResource.servletContext = mockServletContext; + pluginRootResource.allowedAssets.add("app/asset.js"); + pluginRootResource.allowedAssets.add("app/asset.css"); + } + + @Test + public void shouldGetAssetIfAllowed() throws IOException { + // given + String resourceName = "/" + ASSET_DIR + "/" + assetName; + ByteArrayInputStream inputStream = new ByteArrayInputStream(ASSET_CONTENT.getBytes()); + Mockito.doReturn(inputStream).when(mockServletContext).getResourceAsStream(resourceName); + + try { + // when + final Response actual = pluginRootResource.getAsset(assetName); + + // then + if (assetAllowed) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + ((StreamingOutput) actual.getEntity()).write(output); + + assertThat(output.toString()).isEqualTo(ASSET_CONTENT); + assertThat(actual.getHeaders()).containsKey(HttpHeaders.CONTENT_TYPE).hasSize(1); + assertThat(actual.getHeaders().get(HttpHeaders.CONTENT_TYPE)).hasSize(1); + // In IDE it's String, with maven it's MediaType class + assertThat(actual.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0).toString()).isEqualTo(assetMediaType); + + Mockito.verify(runtimeDelegate).getAppPluginRegistry(); + Mockito.verify(pluginRegistry).getPlugin(PLUGIN_NAME); + Mockito.verify(mockServletContext).getResourceAsStream(resourceName); + } else { + fail("should throw RestException for '%s'", assetName); + } + + } catch (RestException e) { + // then + if (assetAllowed) { + e.printStackTrace(); + fail("should not throw RestException for '%s'", assetName); + } else { + assertThat(e).isInstanceOf(RestException.class); + assertThat(e).hasMessage("Not allowed to load the following file '" + assetName + "'."); + + Mockito.verify(runtimeDelegate, Mockito.never()).getAppPluginRegistry(); + Mockito.verify(pluginRegistry, Mockito.never()).getPlugin(PLUGIN_NAME); + Mockito.verify(mockServletContext, Mockito.never()).getResourceAsStream(assetName); + } + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/META-INF/services/org.camunda.bpm.engine.rest.spi.ProcessEngineProvider b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/META-INF/services/org.camunda.bpm.engine.rest.spi.ProcessEngineProvider new file mode 100644 index 0000000000000000000000000000000000000000..c52f72c1266582bf7316c8584a1290b3d7d5ac13 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/META-INF/services/org.camunda.bpm.engine.rest.spi.ProcessEngineProvider @@ -0,0 +1 @@ +org.camunda.bpm.engine.rest.impl.application.ContainerManagedProcessEngineProvider \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/changed_cookie_name_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/changed_cookie_name_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..cca3687f4e51c871b1da36ebaac8210cd1aa5f7a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/changed_cookie_name_web.xml @@ -0,0 +1,22 @@ + + + + Camunda Platform webapp + + + CsrfPreventionFilter + org.camunda.bpm.webapp.impl.security.filter.CsrfPreventionFilter + + cookieName + myCookieName + + + + CsrfPreventionFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/ignore_case_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/ignore_case_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..02f7f664a3a258cfb2fa41be459b7267f21a4d88 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/ignore_case_web.xml @@ -0,0 +1,26 @@ + + + + Camunda Platform webapp + + + CsrfPreventionFilter + org.camunda.bpm.webapp.impl.security.filter.CsrfPreventionFilter + + enableSecureCookie + trUe + + + sameSiteCookieOption + lAx + + + + CsrfPreventionFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_custom_value_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_custom_value_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..c324f0daefa3c9b1ddb703532fccde3aa95179c2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_custom_value_web.xml @@ -0,0 +1,22 @@ + + + + Camunda Platform webapp + + + CsrfPreventionFilter + org.camunda.bpm.webapp.impl.security.filter.CsrfPreventionFilter + + sameSiteCookieValue + aCustomValue + + + + CsrfPreventionFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_disabled_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_disabled_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..fcdb7f9c40f2c0e2e552df728c0d922b0713eaac --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_disabled_web.xml @@ -0,0 +1,22 @@ + + + + Camunda Platform webapp + + + CsrfPreventionFilter + org.camunda.bpm.webapp.impl.security.filter.CsrfPreventionFilter + + enableSameSiteCookie + false + + + + CsrfPreventionFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_option_lax_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_option_lax_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..48fea40dfcba8f51521d9589c2774c937a9f83f3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_option_lax_web.xml @@ -0,0 +1,22 @@ + + + + Camunda Platform webapp + + + CsrfPreventionFilter + org.camunda.bpm.webapp.impl.security.filter.CsrfPreventionFilter + + sameSiteCookieOption + lax + + + + CsrfPreventionFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_option_strict_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_option_strict_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..2cb74037bec820fc3046ce2d8831b1c58fb641f9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_option_strict_web.xml @@ -0,0 +1,22 @@ + + + + Camunda Platform webapp + + + CsrfPreventionFilter + org.camunda.bpm.webapp.impl.security.filter.CsrfPreventionFilter + + sameSiteCookieOption + strict + + + + CsrfPreventionFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_option_unknown_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_option_unknown_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..b127ed9cf05c58b8b5f1b87d0f049d0ee825f2cb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_option_unknown_web.xml @@ -0,0 +1,22 @@ + + + + Camunda Platform webapp + + + CsrfPreventionFilter + org.camunda.bpm.webapp.impl.security.filter.CsrfPreventionFilter + + sameSiteCookieOption + anUnknownOption + + + + CsrfPreventionFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_option_value_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_option_value_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..842ab4c350d1dbfe0abd5170a07f716cb8dfea47 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/same_site_option_value_web.xml @@ -0,0 +1,26 @@ + + + + Camunda Platform webapp + + + CsrfPreventionFilter + org.camunda.bpm.webapp.impl.security.filter.CsrfPreventionFilter + + sameSiteCookieOption + strict + + + sameSiteCookieValue + aCustomValue + + + + CsrfPreventionFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/secure_enabled_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/secure_enabled_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..c47fab45e3c0d76dca84a5daff1a916edf4d42fb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/secure_enabled_web.xml @@ -0,0 +1,22 @@ + + + + Camunda Platform webapp + + + CsrfPreventionFilter + org.camunda.bpm.webapp.impl.security.filter.CsrfPreventionFilter + + enableSecureCookie + true + + + + CsrfPreventionFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/web.xml new file mode 100644 index 0000000000000000000000000000000000000000..e22eb937c125ec8ccf3947928eaaa2ce2033d873 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/csrf/web.xml @@ -0,0 +1,18 @@ + + + + Camunda Platform webapp + + + CsrfPreventionFilter + org.camunda.bpm.webapp.impl.security.filter.CsrfPreventionFilter + + + CsrfPreventionFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/csp/custom_value_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/csp/custom_value_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..1f8afbcc584d59af52bfcedb8194bfb3a4eb1a8c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/csp/custom_value_web.xml @@ -0,0 +1,29 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + contentSecurityPolicyValue + + base-uri 'self'; + default-src 'self' 'unsafe-inline'; + img-src 'self' data:; + block-all-mixed-content + + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/csp/disabled_ignore_case_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/csp/disabled_ignore_case_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..2774c5d6a4a14e0861b3b4d42ae46cb25da83da3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/csp/disabled_ignore_case_web.xml @@ -0,0 +1,24 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + contentSecurityPolicyDisabled + TRUe + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/csp/disabled_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/csp/disabled_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..4a15c0aa84be10680f1661b82c161f2233bdd812 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/csp/disabled_web.xml @@ -0,0 +1,24 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + contentSecurityPolicyDisabled + true + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/cto/custom_value_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/cto/custom_value_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..5f304f6c3da98bacf4d54043d3468c01418fb426 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/cto/custom_value_web.xml @@ -0,0 +1,24 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + contentTypeOptionsValue + aCustomValue + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/cto/disabled_ignore_case_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/cto/disabled_ignore_case_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..49185ee135a5cf010d134dee4903fa54e4a6e954 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/cto/disabled_ignore_case_web.xml @@ -0,0 +1,24 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + contentTypeOptionsDisabled + TrUe + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/cto/disabled_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/cto/disabled_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..112fc35532370a93fb6126353739a9795d64c5b9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/cto/disabled_web.xml @@ -0,0 +1,24 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + contentTypeOptionsDisabled + true + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/custom_value_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/custom_value_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..5fdb85391c621ed1907c84d576392f62ae290f6a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/custom_value_web.xml @@ -0,0 +1,30 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + + hstsValue + aCustomValue + + + + hstsDisabled + false + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/enabled_ignore_case_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/enabled_ignore_case_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..f92a773cced0de01b4f87ca06f1c18c59464b1d2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/enabled_ignore_case_web.xml @@ -0,0 +1,25 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + + hstsDisabled + FaLsE + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/enabled_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/enabled_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..39f1da187fcbf7e8085839c56c2cd8437b229227 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/enabled_web.xml @@ -0,0 +1,25 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + + hstsDisabled + false + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/include_subdomains_max_age_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/include_subdomains_max_age_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..acb53b26d670e5b0f454ffbdded45ac15bcc8abf --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/include_subdomains_max_age_web.xml @@ -0,0 +1,35 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + + hstsMaxAge + 47 + + + + hstsIncludeSubdomainsDisabled + false + + + + hstsDisabled + false + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/include_subdomains_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/include_subdomains_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..8f9c145ccdeaf49206b7cdffa4a87729b1a0e471 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/include_subdomains_web.xml @@ -0,0 +1,30 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + + hstsIncludeSubdomainsDisabled + false + + + + hstsDisabled + false + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/max_age_and_value_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/max_age_and_value_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..3e8b643aacb22eabc766696ae13437bc6ce2724d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/max_age_and_value_web.xml @@ -0,0 +1,35 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + + hstsMaxAge + 47 + + + + hstsValue + aCustomValue + + + + hstsDisabled + false + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/max_age_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/max_age_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..a9cca043d5004994dcdc10e40d4db28431a1b85e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/hsts/max_age_web.xml @@ -0,0 +1,30 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + + hstsMaxAge + 47 + + + + hstsDisabled + false + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/web.xml new file mode 100644 index 0000000000000000000000000000000000000000..4dfa3f555002e7e90ba4f457df3bc29bdaa878d9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/web.xml @@ -0,0 +1,20 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/custom_value_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/custom_value_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..8b9af6451659a86ae0f53221b271ab3bf176e3ff --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/custom_value_web.xml @@ -0,0 +1,24 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + xssProtectionValue + aCustomValue + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/disabled_ignore_case_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/disabled_ignore_case_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..3d2007fd7fe7a753ca92150ee518a4c8611c3d22 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/disabled_ignore_case_web.xml @@ -0,0 +1,24 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + xssProtectionDisabled + TrUe + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/disabled_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/disabled_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..2f323d0cc4332dabb1ffc91370ea989dd31a7bd8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/disabled_web.xml @@ -0,0 +1,24 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + xssProtectionDisabled + true + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_and_value_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_and_value_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..7731a4c8fef3d61a6c527843b244241e9e224763 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_and_value_web.xml @@ -0,0 +1,28 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + xssProtectionOption + BLOCK + + + xssProtectionValue + aCustomValue + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_block_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_block_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..856b337a08d4fd2a74244f09a937997ca394dc35 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_block_web.xml @@ -0,0 +1,24 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + xssProtectionOption + BLOCK + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_non_existing_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_non_existing_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..f035cec19700c42ee4cbdca295e3e4075c8e5d54 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_non_existing_web.xml @@ -0,0 +1,24 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + xssProtectionOption + foo + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_sanitize_ignore_case_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_sanitize_ignore_case_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..f9f98d7f9b8e3b3dea9808c4dddb7c6fd44e41be --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_sanitize_ignore_case_web.xml @@ -0,0 +1,24 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + xssProtectionOption + sanitize + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_sanitize_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_sanitize_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..16528acfeb22944a8fdb581f8f4abafe7a1c90eb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/headersec/xss/option_sanitize_web.xml @@ -0,0 +1,24 @@ + + + + Camunda Platform webapp + + + HttpHeaderSecurity + org.camunda.bpm.webapp.impl.security.filter.headersec.HttpHeaderSecurityFilter + + xssProtectionOption + SANITIZE + + + + + HttpHeaderSecurity + /* + REQUEST + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/changed_cookie_name_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/changed_cookie_name_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..de5ca2a32f4dfd57c08bd3205b95a67ebb64bd5a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/changed_cookie_name_web.xml @@ -0,0 +1,27 @@ + + + + Camunda Platform webapp + + + org.eclipse.jetty.servlet.SessionCookie + MYCOOKIENAME + + + + SessionCookieFilter + org.camunda.bpm.webapp.impl.security.filter.SessionCookieFilter + + cookieName + MYCOOKIENAME + + + + SessionCookieFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/ignore_case_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/ignore_case_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..de6c2b3e6d124b7befec669d9510ca9095503d37 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/ignore_case_web.xml @@ -0,0 +1,26 @@ + + + + Camunda Platform webapp + + + SessionCookieFilter + org.camunda.bpm.webapp.impl.security.filter.SessionCookieFilter + + enableSecureCookie + trUe + + + sameSiteCookieOption + lAx + + + + SessionCookieFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_custom_value_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_custom_value_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..57d48ab05962e8ab7abe58609ad9fa6e9c8fe280 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_custom_value_web.xml @@ -0,0 +1,22 @@ + + + + Camunda Platform webapp + + + SessionCookieFilter + org.camunda.bpm.webapp.impl.security.filter.SessionCookieFilter + + sameSiteCookieValue + aCustomValue + + + + SessionCookieFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_disabled_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_disabled_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..c0219370fb198ece2fca0d96eee4634345c69af3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_disabled_web.xml @@ -0,0 +1,22 @@ + + + + Camunda Platform webapp + + + SessionCookieFilter + org.camunda.bpm.webapp.impl.security.filter.SessionCookieFilter + + enableSameSiteCookie + false + + + + SessionCookieFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_option_lax_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_option_lax_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..18ac054fe93a9faff72c265ba475e296c5116e84 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_option_lax_web.xml @@ -0,0 +1,22 @@ + + + + Camunda Platform webapp + + + SessionCookieFilter + org.camunda.bpm.webapp.impl.security.filter.SessionCookieFilter + + sameSiteCookieOption + lax + + + + SessionCookieFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_option_strict_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_option_strict_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..8260f3ebfa9a3ce4c56c4abf08a5ec35d5913535 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_option_strict_web.xml @@ -0,0 +1,22 @@ + + + + Camunda Platform webapp + + + SessionCookieFilter + org.camunda.bpm.webapp.impl.security.filter.SessionCookieFilter + + sameSiteCookieOption + strict + + + + SessionCookieFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_option_unknown_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_option_unknown_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..7d5a7dffe1d6702c1f7d91004fddf0ffd9d7aadf --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_option_unknown_web.xml @@ -0,0 +1,22 @@ + + + + Camunda Platform webapp + + + SessionCookieFilter + org.camunda.bpm.webapp.impl.security.filter.SessionCookieFilter + + sameSiteCookieOption + anUnknownOption + + + + SessionCookieFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_option_value_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_option_value_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..5fcfc157c66c0ecc1d7bfb446084bc79dfb45fad --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/same_site_option_value_web.xml @@ -0,0 +1,26 @@ + + + + Camunda Platform webapp + + + SessionCookieFilter + org.camunda.bpm.webapp.impl.security.filter.SessionCookieFilter + + sameSiteCookieOption + strict + + + sameSiteCookieValue + aCustomValue + + + + SessionCookieFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/secure_enabled_web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/secure_enabled_web.xml new file mode 100644 index 0000000000000000000000000000000000000000..465a5c5bf19d8953e33524b557bc67fb253f4bc0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/secure_enabled_web.xml @@ -0,0 +1,22 @@ + + + + Camunda Platform webapp + + + SessionCookieFilter + org.camunda.bpm.webapp.impl.security.filter.SessionCookieFilter + + enableSecureCookie + true + + + + SessionCookieFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/web.xml new file mode 100644 index 0000000000000000000000000000000000000000..8ae8927f6f443bce7b243ee5c4369c46a6c644fc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/WEB-INF/session/web.xml @@ -0,0 +1,18 @@ + + + + Camunda Platform webapp + + + SessionCookieFilter + org.camunda.bpm.webapp.impl.security.filter.SessionCookieFilter + + + SessionCookieFilter + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/camunda-skip-check.cfg.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/camunda-skip-check.cfg.xml new file mode 100644 index 0000000000000000000000000000000000000000..1a95af6249fdface9f0988f5dd5bb2ded9cbe3e6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/camunda-skip-check.cfg.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/camunda-test-engine.cfg.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/camunda-test-engine.cfg.xml new file mode 100644 index 0000000000000000000000000000000000000000..ad885c79b09e48b753b6e1a125084ddb4801d706 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/camunda-test-engine.cfg.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/camunda.cfg.prefix.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/camunda.cfg.prefix.xml new file mode 100644 index 0000000000000000000000000000000000000000..526942393dfccf8d801beab89ff0636ab44b7d5f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/camunda.cfg.prefix.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/camunda.cfg.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/camunda.cfg.xml new file mode 100644 index 0000000000000000000000000000000000000000..14f00ef3a41806a99e83658843bf3e31fbbd73a7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/camunda.cfg.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/logback-test.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/logback-test.xml new file mode 100644 index 0000000000000000000000000000000000000000..20348a9d43b7be9af5c7d95625ec6ed58e528424 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/logback-test.xml @@ -0,0 +1,31 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/another-failing-process.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/another-failing-process.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..27b314c3b339ba25b9b03820020fc11f8aa2eb11 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/another-failing-process.bpmn @@ -0,0 +1,39 @@ + + + + + SequenceFlow_1 + + + SequenceFlow_1 + SequenceFlow_2 + + + + SequenceFlow_2 + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/another-user-task-process.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/another-user-task-process.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..ead47f8de91f2c9f9ecfeea20c70b7b48d35b267 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/another-user-task-process.bpmn @@ -0,0 +1,39 @@ + + + + + SequenceFlow_1 + + + SequenceFlow_1 + SequenceFlow_2 + + + + SequenceFlow_2 + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/call-activity.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/call-activity.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..4ad22c2082810588ccbecd205949f0e0bb33dbb4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/call-activity.bpmn @@ -0,0 +1,45 @@ + + + + + SequenceFlow_1 + + + SequenceFlow_1 + SequenceFlow_2 + + + + + SequenceFlow_2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/calling-user-task-process.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/calling-user-task-process.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..fab1416db15958ba6cdb690deea79307a384a90e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/calling-user-task-process.bpmn @@ -0,0 +1,45 @@ + + + + + SequenceFlow_1 + + + SequenceFlow_1 + SequenceFlow_2 + + + + + SequenceFlow_2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/dynamic-call-activity.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/dynamic-call-activity.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..38912c807ca0097d4d5ddb2a2e3265f7f6f5a656 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/dynamic-call-activity.bpmn @@ -0,0 +1,42 @@ + + + + + SequenceFlow_1 + + + SequenceFlow_1 + SequenceFlow_2 + + + + SequenceFlow_2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/failing-process.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/failing-process.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..69dfe982d8b0731b766070b5cfb4897285b50b88 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/failing-process.bpmn @@ -0,0 +1,39 @@ + + + + + SequenceFlow_1 + + + SequenceFlow_1 + SequenceFlow_2 + + + + SequenceFlow_2 + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/finished-process.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/finished-process.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..80cc17257638c1a12e0b7dbb3cb64e96840e3013 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/finished-process.bpmn @@ -0,0 +1,51 @@ + + + + + SequenceFlow_1 + + + + SequenceFlow_2 + + + SequenceFlow_1 + SequenceFlow_2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/multi-tenancy-call-activity.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/multi-tenancy-call-activity.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..1c8604375b2bdf4991338d285978a8c078204f84 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/multi-tenancy-call-activity.bpmn @@ -0,0 +1,117 @@ + + + + + SequenceFlow_14pyocq + + + + + SequenceFlow_14pyocq + SequenceFlow_0o717yf + SequenceFlow_0kmxlbt + + + + + SequenceFlow_1xa7203 + SequenceFlow_1k924eo + SequenceFlow_139miyl + + + + SequenceFlow_139miyl + + + + SequenceFlow_0kmxlbt + SequenceFlow_1xa7203 + + + SequenceFlow_0o717yf + SequenceFlow_1k924eo + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/nested-call-activity.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/nested-call-activity.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..0b2dab3d868b0dc29b234cf4175604b20ac1dd59 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/nested-call-activity.bpmn @@ -0,0 +1,45 @@ + + + + + SequenceFlow_1 + + + SequenceFlow_1 + SequenceFlow_2 + + + + + SequenceFlow_2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/nested-calling-user-task-process.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/nested-calling-user-task-process.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..d95a61ede04d506d559eae6e2ccf65d09385b641 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/nested-calling-user-task-process.bpmn @@ -0,0 +1,45 @@ + + + + + SequenceFlow_1 + + + SequenceFlow_1 + SequenceFlow_2 + + + + + SequenceFlow_2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/process-with-two-parallel-failing-services.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/process-with-two-parallel-failing-services.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..be67d3e998605206778d6f928c8df73d74a77c90 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/process-with-two-parallel-failing-services.bpmn @@ -0,0 +1,128 @@ + + + + + SequenceFlow_7 + SequenceFlow_2 + SequenceFlow_3 + + + + SequenceFlow_2 + SequenceFlow_4 + + + + + SequenceFlow_3 + SequenceFlow_5 + + + SequenceFlow_4 + SequenceFlow_5 + SequenceFlow_6 + + + + + SequenceFlow_6 + + + + SequenceFlow_1 + + + + SequenceFlow_1 + SequenceFlow_7 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/simple-user-task-process.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/simple-user-task-process.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..51b0558e23073c1de53a09bea85b163fe5011e94 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/simple-user-task-process.bpmn @@ -0,0 +1,39 @@ + + + + + SequenceFlow_1 + + + SequenceFlow_1 + SequenceFlow_2 + + + + SequenceFlow_2 + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/two-parallel-call-activities-calling-different-process.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/two-parallel-call-activities-calling-different-process.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..6ab73bbb1e308d993503840145e0fea0269e5eb3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/two-parallel-call-activities-calling-different-process.bpmn @@ -0,0 +1,122 @@ + + + + + SequenceFlow_1 + SequenceFlow_2 + SequenceFlow_3 + + + + + + + + SequenceFlow_3 + SequenceFlow_5 + + + + + + + SequenceFlow_2 + SequenceFlow_4 + + + + SequenceFlow_4 + SequenceFlow_5 + SequenceFlow_6 + + + + SequenceFlow_6 + + + SequenceFlow_1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/two-parallel-call-activities-calling-same-process.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/two-parallel-call-activities-calling-same-process.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..19d73c498cdd275f20f2a913785a4e65c13e39bc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/two-parallel-call-activities-calling-same-process.bpmn @@ -0,0 +1,116 @@ + + + + + SequenceFlow_1 + SequenceFlow_2 + SequenceFlow_3 + + + + + SequenceFlow_3 + SequenceFlow_5 + + + + SequenceFlow_2 + SequenceFlow_4 + + + + SequenceFlow_4 + SequenceFlow_5 + SequenceFlow_6 + + + + SequenceFlow_6 + + + SequenceFlow_1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/user-task-process.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/user-task-process.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..cc96c295678f052c0683c736a17bf0933783d7e9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/user-task-process.bpmn @@ -0,0 +1,39 @@ + + + + + SequenceFlow_1 + + + SequenceFlow_1 + SequenceFlow_2 + + + + SequenceFlow_2 + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/variables-process-with-call-activity.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/variables-process-with-call-activity.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..3fd6678529b4fc690be5ae27954d3ca6d9471c45 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/variables-process-with-call-activity.bpmn @@ -0,0 +1,54 @@ + + + + + SequenceFlow_1 + + + + SequenceFlow_1 + SequenceFlow_4 + + + SequenceFlow_5 + + + SequenceFlow_4 + SequenceFlow_5 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/variables-process.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/variables-process.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..46c57ff0acb7ff50e74490f2bd71bbc90750e7ef --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/assembly/src/test/resources/processes/variables-process.bpmn @@ -0,0 +1,54 @@ + + + + + SequenceFlow_1 + + + + SequenceFlow_1 + SequenceFlow_2 + + + SequenceFlow_2 + SequenceFlow_3 + + + + SequenceFlow_3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.babelrc b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.babelrc new file mode 100644 index 0000000000000000000000000000000000000000..b24fc309f443397537084755b97f6a60aad1ca93 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.babelrc @@ -0,0 +1,18 @@ +{ + "presets": [ + // "env", + [ + "@babel/preset-env", + { + "corejs": 3, + "modules": "commonjs", // resolves https://github.com/noppa/ng-hot-reload/issues/31 + "shippedProposals": true, + "useBuiltIns": "usage" + } + ] + ], + "plugins": [ + "@babel/plugin-transform-object-rest-spread", + "@babel/plugin-transform-object-assign" + ] +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.eslintignore b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.eslintignore new file mode 100644 index 0000000000000000000000000000000000000000..7e66ec11118622a0bbf93164d3b589f106d5148c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.eslintignore @@ -0,0 +1,4 @@ +node_modules/**/*.js +**/*test*/**/*.js +target/ +node/ diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.eslintrc b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..e1a810c4bcc211e122ca752fbe5ce228f9f86024 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.eslintrc @@ -0,0 +1,50 @@ +{ + "rules": { + "space-before-blocks": [ 2, "always"], + "space-before-function-paren": [ 2, "never" ], + "semi": [ 2, "always" ], + "no-console": 1, + "no-self-assign": 0, + "no-useless-escape": "off", + "i18n-json/sorted-keys": [2, { + "order": "asc", + "indentSpaces": 2 + }], + "i18n-json/valid-json": 0, + "i18n-json/valid-message-syntax": 0 + }, + "env": { + "node": true, + "browser": true, + "es6": true + }, + "overrides": [ + { + "files": ["*.json"], + "rules": { + "license-header/header": "off", + "prettier/prettier": "off" + } + } + ], + "extends": [ + "eslint:recommended", + "plugin:camunda-licensed/apache", + "plugin:prettier/recommended", + "plugin:i18n-json/recommended" + ], + "parserOptions": { + "ecmaVersion": 2020, + "sourceType": "module" + }, + "globals": { + "requirejs": false, + "expect": false, + "it": false, + "describe": false, + "beforeEach": true, + "afterEach": true, + "before": true, + "after": true + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.gitignore b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c5291250a40f001500897b715f55914dae01d5a6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.gitignore @@ -0,0 +1,24 @@ +.idea/ +.classpath +.project +.settings +build.properties +bin/ +.metadata +transaction.log +nbactions*.xml +nb-configuration.xml +faces-config.NavData +*.iml +*.sublime-project +*.sublime-workspace +*.h2.db +*.lock.db +test.*.log +webapp/*.log +debug.log +test-results +node_modules/ +dist/ +node/ +target/ diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.npmrc b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.npmrc new file mode 100644 index 0000000000000000000000000000000000000000..a6a6b4635e1b540de74a0e71214fe9c56d866ce4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.npmrc @@ -0,0 +1 @@ +#registry = https://artifacts.camunda.com/artifactory/npm-public/ diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.prettierrc b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.prettierrc new file mode 100644 index 0000000000000000000000000000000000000000..a1f6f20fb6594ba19f2d6415035b9653511c2d6c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.prettierrc @@ -0,0 +1,9 @@ +{ + "tabWidth": 2, + "semi": true, + "singleQuote": true, + "bracketSpacing": false, + "endOfLine": "auto", + "printWidth": 80, + "useTabs": false +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.stylelintrc.json b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.stylelintrc.json new file mode 100644 index 0000000000000000000000000000000000000000..1d8d9d7185b0fabf5d219eb45844584449fb20e5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/.stylelintrc.json @@ -0,0 +1,6 @@ +{ + "extends": "stylelint-config-standard", + "rules": { + "no-invalid-position-at-import-rule": null + } +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.eslintignore b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.eslintignore new file mode 100644 index 0000000000000000000000000000000000000000..7c18d32814af285048a69308e93cdcb83a97e11c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.eslintignore @@ -0,0 +1,2 @@ +node_modules/**/*.js +*/test/** \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.eslintrc b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..ca46959da8715aec19665a966cfa73f224bd3a56 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.eslintrc @@ -0,0 +1,32 @@ +{ + "rules": { + "space-before-blocks": [ 2, "always"], + "space-before-function-paren": [ 2, "never" ], + "semi": [ 2, "always" ], + "no-console": 1, + "no-useless-escape": "off" + }, + "env": { + "node": true, + "browser": true, + "es6": true + }, + "extends": [ + "eslint:recommended", + "plugin:camunda-licensed/apache", + "plugin:prettier/recommended" + ], + "parserOptions": { + "sourceType": "module", + }, + "globals": { + "requirejs": false, + "expect": false, + "it": false, + "describe": false, + "beforeEach": true, + "afterEach": true, + "before": true, + "after": true + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.gitignore b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..d1cd6e649714a82ac2f11f5320274bff8f217d83 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.gitignore @@ -0,0 +1,11 @@ +node_modules +*.swp +*.log +documentation +dist +/.project +.idea/ +staging/ +camunda-bpm-sdk* +vendor/superagent/index.js +vendor/fast-xml-parser/index.js \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.jshintrc b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.jshintrc new file mode 100644 index 0000000000000000000000000000000000000000..8921afac8a05c1fa523a908f9901c3e87b791e6c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.jshintrc @@ -0,0 +1,21 @@ +{ + "globals": { + "browser": false, + "element": false, + "by": false, + "describe": false, + "xdescribe": false, + "ddescribe": false, + "it": false, + "xit": false, + "expect": false, + "beforeEach": false, + "afterEach": false, + "runs": false, + "waitsFor": false + }, + "node": true, + "browser": true, + "indent": 2, + "strict": true +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.npmrc b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.npmrc new file mode 100644 index 0000000000000000000000000000000000000000..a6a6b4635e1b540de74a0e71214fe9c56d866ce4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.npmrc @@ -0,0 +1 @@ +#registry = https://artifacts.camunda.com/artifactory/npm-public/ diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.prettierrc b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.prettierrc new file mode 100644 index 0000000000000000000000000000000000000000..1ece59cb6b06085acb565861ccca5b05e673bf1c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/.prettierrc @@ -0,0 +1,6 @@ +{ + "tabWidth": 2, + "semi": true, + "singleQuote": true, + "bracketSpacing": false +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/CONTRIBUTING.md b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..4cf457c9ee07d8ddf1801c6c21f5b08ffd1820d0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/CONTRIBUTING.md @@ -0,0 +1,12 @@ +# How to Contribute + +## Writing Docs + +All docs are written in Markdown and are located in the `doc/` folder. + +### Markdown editing guidelines: + +* Use pure Markdown (as opposed to embedded HTML) as much as possible. +* Markdown files should use a linewrap at 100 characters. +* All links must use the id-scheme and references must be placed at the end of the document. + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/LICENSE b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d0381d6d04c77c78c42ae875f97d38483ba0c636 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/LICENSE @@ -0,0 +1,176 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/README.md b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f42df9dd38a27656e313e0e91dc9304561a2a976 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/README.md @@ -0,0 +1,107 @@ +# camunda-bpm-sdk-js + +Javascript client library for [Camunda Platform](https://github.com/camunda/camunda-bpm-platform) + +## Install using bower + +```sh +bower install camunda-bpm-sdk-js --save +``` + +## Documentation + +See https://docs.camunda.org/manual/latest/reference/embedded-forms/ + +## Development + +```sh +npm install +``` + +```sh +grunt auto-build +``` + +### Testing + +#### Karma + +```sh +grunt karma +``` + +Alternatively, you can use the specific targets + +```sh +grunt karma:dev-form +# or +grunt karma:dev-form-angularjs +``` + + +#### Mocha CLI + +```sh +grunt mochacli +# or +grunt watch:mochacli +``` + +### Issues + +https://app.camunda.com/jira/browse/CAM/component/12351 + +## Releasing + +### Release + +To create a release: + +```sh +grunt publish:release --setversion='myReleaseVersion' +``` + +This will update the version, commit and tag it, then publish it to [bower-camunda-bpm-sdk-js](https://github.com/camunda/bower-camunda-bpm-sdk-js) + +### Snapshot + +To create a snapshot release which just builds current head and publishes it to [bower-camunda-bpm-sdk-js](https://github.com/camunda/bower-camunda-bpm-sdk-js) on a branch named the current version: + +```sh +grunt publish:snapshot +``` + +### Version + +If you just want to update the current version: + +```sh +grunt publish:version --setversion='myNewVersion' +``` + +### Available options + +* --no-bower -> skip bower release +* --no-write -> dryRun mode + +### Examples + +* [standalone usage](https://github.com/camunda/camunda-bpm-examples/tree/master/sdk-js) + +### Contributing + +You are __more than welcome__ to take part on the development of this project! + +#### Coding + +Clone the repository, add, fix or improve and send us a pull request. +But please take care about the commit messages, [our conventions can be found +here](https://github.com/camunda/camunda-bpm-platform/blob/master/CONTRIBUTING.md). + +#### Coding style guide + +In place of a guide, just follow the formatting of existing code :-) + +## License + +The source files in this repository are made available under the [Apache License Version 2.0](./LICENSE). diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/index.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1c93202b0eba301da5bda86dc620ff976e8dc25a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/index.js @@ -0,0 +1,18 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +module.exports = require('./lib/index'); diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/angularjs/forms/camunda-form-angular.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/angularjs/forms/camunda-form-angular.js new file mode 100644 index 0000000000000000000000000000000000000000..09f7bf59d05f42529eb81a8b3c537cca0b7b1949 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/angularjs/forms/camunda-form-angular.js @@ -0,0 +1,137 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +// exposify: CamSDK.Form +var CamundaForm = require('./../../forms/camunda-form'); + +var angular = require('angular'); +var $ = CamundaForm.$; +var constants = require('./../../forms/constants'); + +var CamundaFormAngular = CamundaForm.extend({ + renderForm: function() { + var self = this; + + this.formElement = angular.element(this.formElement); + + // first add the form to the DOM: + CamundaForm.prototype.renderForm.apply(this, arguments); + + // next perform auto-scope binding for all fields which do not have custom bindings + function autoBind(key, el) { + var element = $(el); + if (!element.attr('ng-model')) { + var camVarName = element.attr(constants.DIRECTIVE_CAM_VARIABLE_NAME); + if (camVarName) { + element.attr('ng-model', camVarName); + } + } + } + + for (var i = 0; i < this.formFieldHandlers.length; i++) { + var handler = this.formFieldHandlers[i]; + var selector = handler.selector; + $(selector, self.formElement).each(autoBind); + } + + this.formElement = angular.element(this.formElement); + // finally compile the form with angular and linked to the current scope + var injector = self.formElement.injector(); + if (!injector) { + return; + } + + var scope = self.formElement.scope(); + injector.invoke([ + '$compile', + function($compile) { + $compile(self.formElement)(scope); + } + ]); + scope.camForm = this; + }, + + executeFormScript: function(script) { + // overrides executeFormScript to make sure the following variables / functions are available to script implementations: + + // * $scope + // * inject + + this.formElement = angular.element(this.formElement); + + var moment = require('moment'); + var injector = this.formElement.injector(); + var scope = this.formElement.scope(); + + /*eslint-disable */ + (function(camForm, $scope, moment) { + // hook to create the service with injection + var inject = function(extensions) { + // if result is an array or function we expect + // an injectable service + if (angular.isFunction(extensions) || angular.isArray(extensions)) { + injector.instantiate(extensions, { $scope: scope }); + } else { + throw new Error('Must call inject(array|fn)'); + } + }; + + /* jshint evil: true */ + eval(script); + /* jshint evil: false */ + + })(this, scope, moment); + /*eslint-enable */ + }, + + fireEvent: function() { + // overrides fireEvent to make sure event listener is invoked in an apply phase + this.formElement = angular.element(this.formElement); + + var self = this; + var args = arguments; + var scope = this.formElement.scope(); + + var doFireEvent = function() { + CamundaForm.prototype.fireEvent.apply(self, args); + }; + + var injector = self.formElement.injector(); + if (!injector) { + return; + } + + injector.invoke([ + '$rootScope', + function($rootScope) { + var phase = $rootScope.$$phase; + // only apply if not already in digest / apply + if (phase !== '$apply' && phase !== '$digest') { + scope.$apply(function() { + doFireEvent(); + }); + } else { + doFireEvent(); + } + } + ]); + } +}); + +module.exports = CamundaFormAngular; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/angularjs/forms/index.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/angularjs/forms/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1d246acf9009acaa3ae8c556000d3209549ae0b0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/angularjs/forms/index.js @@ -0,0 +1,102 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var angular = require('angular'), + CamundaFormAngular = require('./camunda-form-angular'), + isType = require('./../../forms/type-util').isType; + +// define embedded forms angular module +var ngModule = angular.module('cam.embedded.forms', []); + +/** + * Exposes 'cam-variable-name' as angular directive making sure + * that updates to a HTML Control made through the camunda form + * infrastructure are propagated over ngModel bindings. + */ +ngModule.directive('camVariableName', [ + '$rootScope', + function($rootScope) { + return { + require: 'ngModel', + link: function(scope, elm, attrs, ctrl) { + elm.on('camFormVariableApplied', function(evt, value) { + var phase = $rootScope.$$phase; + // only apply if not already in digest / apply + if (phase !== '$apply' && phase !== '$digest') { + scope.$apply(function() { + ctrl.$setViewValue(value); + }); + } else { + ctrl.$setViewValue(value); + } + }); + } + }; + } +]); + +ngModule.directive('camVariableType', [ + function() { + return { + require: 'ngModel', + link: function($scope, $element, $attrs, ctrl) { + var validate = function(viewValue) { + var type = $attrs.camVariableType; + + ctrl.$setValidity('camVariableType', true); + + if (viewValue || viewValue === false || type === 'Bytes') { + if ( + ['Boolean', 'String', 'Bytes'].indexOf(type) === -1 && + !isType(viewValue, type) + ) { + ctrl.$setValidity('camVariableType', false); + } + + if ( + $attrs.type === 'file' && + type === 'Bytes' && + $element[0].files && + $element[0].files[0] && + $element[0].files[0].size > ($attrs.camMaxFilesize || 5000000) + ) { + ctrl.$setValidity('camVariableType', false); + } + } + + return viewValue; + }; + + ctrl.$parsers.unshift(validate); + ctrl.$formatters.push(validate); + + $attrs.$observe('camVariableType', function() { + return validate(ctrl.$viewValue); + }); + + $element.bind('change', function() { + validate(ctrl.$viewValue); + $scope.$apply(); + }); + } + }; + } +]); + +module.exports = CamundaFormAngular; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/angularjs/index.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/angularjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..213f78ccc4d8c781b3c81fa09d6d6367ecdbbbe3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/angularjs/index.js @@ -0,0 +1,24 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** @namespace CamSDK */ + +module.exports = { + Client: require('./../api-client'), + Form: require('./forms'), + utils: require('./../utils') +}; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/abstract-client-resource.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/abstract-client-resource.js new file mode 100644 index 0000000000000000000000000000000000000000..f8455ecb2f58f1739ba2d7bb1012a58b8f762832 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/abstract-client-resource.js @@ -0,0 +1,279 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +// var HttpClient = require('./http-client'); +var Q = require('q'); +var Events = require('./../events'); +var BaseClass = require('./../base-class'); + +/** + * No-Op callback + */ +function noop() {} + +/** + * Abstract class for resources + * + * @class + * @augments {CamSDK.BaseClass} + * @memberof CamSDK.client + * + * @borrows CamSDK.Events.on as on + * @borrows CamSDK.Events.once as once + * @borrows CamSDK.Events.off as off + * @borrows CamSDK.Events.trigger as trigger + * + * @borrows CamSDK.Events.on as prototype.on + * @borrows CamSDK.Events.once as prototype.once + * @borrows CamSDK.Events.off as prototype.off + * @borrows CamSDK.Events.trigger as prototype.trigger + * + * + * @example + * + * // create a resource Model + * var Model = AbstractClientResource.extend({ + * apiUri: 'path-to-the-endpoint' + * doSomethingOnInstance: function() { + * // + * } + * }, { + * somethingStatic: {} + * }); + * + * // use the generated Model statically + * // with events + * Model.on('eventname', function(results) { + * // You probably have something like + * var total = results.count; + * var instances = results.items; + * }); + * Model.list({ nameLike: '%call%' }); + * + * // or alternatively by using a callback + * Model.list({ nameLike: '%call%' }, function(err, results) { + * if (err) { + * throw err; + * } + * + * var total = results.count; + * var instances = results.items; + * }); + * + * var instance = new Model(); + * instance.claim(function(err, result) { + * + * }); + */ +var AbstractClientResource = BaseClass.extend( + /** @lends AbstractClientResource.prototype */ + { + /** + * Initializes a AbstractClientResource instance + * + * This method is aimed to be overriden by other implementations + * of the AbstractClientResource. + * + * @method initialize + */ + initialize: function() { + // do something to initialize the instance + // like copying the Model http property to the "this" (instanciated) + this.http = this.constructor.http; + } + }, + + /** @lends AbstractClientResource */ + { + /** + * Path used by the resource to perform HTTP queries + * + * @abstract + * @memberOf CamSDK.client.AbstractClientResource + */ + path: '', + + /** + * Object hosting the methods for HTTP queries. + * + * @abstract + * @memberof CamSDK.client.AbstractClientResource + */ + http: {}, + + /** + * Create an instance on the backend + * + * @abstract + * @memberOf CamSDK.client.AbstractClientResource + * + * @param {!Object|Object[]} attributes + * @param {requestCallback} [done] + */ + create: function() {}, + + /** + * Fetch a list of instances + * + * @memberof CamSDK.client.AbstractClientResource + * + * @fires CamSDK.AbstractClientResource#error + * @fires CamSDK.AbstractClientResource#loaded + * + * @param {?Object.} params + * @param {requestCallback} [done] + */ + list: function(params, done) { + // allows to pass only a callback + if (typeof params === 'function') { + done = params; + params = {}; + } + params = params || {}; + done = done || noop; + + // var likeExp = /Like$/; + var self = this; + var results = { + count: 0, + items: [] + }; + + var combinedPromise = Q.defer(); + + var countFinished = false; + var listFinished = false; + + var checkCompletion = function() { + if (listFinished && countFinished) { + self.trigger('loaded', results); + combinedPromise.resolve(results); + done(null, results); + } + }; + + // until a new webservice is made available, + // we need to perform 2 requests. + // Since they are independent requests, make them asynchronously + self.count(params, function(err, count) { + if (err) { + self.trigger('error', err); + combinedPromise.reject(err); + done(err); + } else { + results.count = count; + countFinished = true; + checkCompletion(); + } + }); + + self.http.get(self.path, { + data: params, + done: function(err, itemsRes) { + if (err) { + self.trigger('error', err); + combinedPromise.reject(err); + done(err); + } else { + results.items = itemsRes; + // QUESTION: should we return that too? + results.firstResult = parseInt(params.firstResult || 0, 10); + results.maxResults = + results.firstResult + parseInt(params.maxResults || 10, 10); + listFinished = true; + checkCompletion(); + } + } + }); + + return combinedPromise.promise; + }, + + /** + * Fetch a count of instances + * + * @memberof CamSDK.client.AbstractClientResource + * + * @fires CamSDK.AbstractClientResource#error + * @fires CamSDK.AbstractClientResource#loaded + * + * @param {?Object.} params + * @param {requestCallback} [done] + */ + count: function(params, done) { + // allows to pass only a callback + if (typeof params === 'function') { + done = params; + params = {}; + } + params = params || {}; + done = done || noop; + var self = this; + var deferred = Q.defer(); + + this.http.get(this.path + '/count', { + data: params, + done: function(err, result) { + if (err) { + /** + * @event CamSDK.AbstractClientResource#error + * @type {Error} + */ + self.trigger('error', err); + + deferred.reject(err); + done(err); + } else { + deferred.resolve(result.count); + done(null, result.count); + } + } + }); + + return deferred.promise; + }, + + /** + * Update one or more instances + * + * @abstract + * @memberof CamSDK.AbstractClientResource + * + * @param {!String|String[]} ids + * @param {Object.} attributes + * @param {requestCallback} [done] + */ + update: function() {}, + + /** + * Delete one or more instances + * + * @abstract + * @memberof CamSDK.AbstractClientResource + * + * @param {!String|String[]} ids + * @param {requestCallback} [done] + */ + delete: function() {} + } +); + +Events.attach(AbstractClientResource); + +module.exports = AbstractClientResource; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/helpers.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..51dbd42cc13c9d798e924f5124149a950759d5a0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/helpers.js @@ -0,0 +1,32 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +exports.createSimpleGetQueryFunction = function(urlSuffix) { + return function(params, done) { + var url = this.path + urlSuffix; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(url, { + data: params, + done: done + }); + }; +}; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/http-client.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/http-client.js new file mode 100644 index 0000000000000000000000000000000000000000..71802b7248e68c53553f7c0a17c4d9ca287bf417 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/http-client.js @@ -0,0 +1,244 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var request = require('superagent'); +var Q = require('q'); +var Events = require('./../events'); +var utils = require('./../utils'); + +/** + * No-Op callback + */ +function noop() {} + +/** + * HttpClient + * + * A HTTP request abstraction layer to be used in node.js / browsers environments. + * + * @class + * @memberof CamSDK.client + */ +var HttpClient = function(config) { + config = config || {}; + + config.headers = config.headers || {}; + if (!config.headers.Accept) { + config.headers.Accept = 'application/hal+json, application/json; q=0.5'; + } + + if (!config.baseUrl) { + throw new Error('HttpClient needs a `baseUrl` configuration property.'); + } + + Events.attach(this); + + this.config = config; +}; + +function end(self, done, deferred) { + done = done || noop; + return function(err, response) { + // TODO: investigate the possible problems related to response without content + if (err || (!response.ok && !response.noContent)) { + err = + err || + response.error || + new Error( + 'The ' + + response.req.method + + ' request on ' + + response.req.url + + ' failed' + ); + if (response && response.body) { + if (response.body.message) { + err.message = response.body.message; + } + } + self.trigger('error', err); + if (deferred) { + deferred.reject(err); + } + return done(err, null, response.headers); + } + + // superagent puts the parsed data into a property named "body" + // and the "raw" content in property named "text" + // and.. it does not parse the response if it does not have + // the "application/json" type. + if (response.type === 'application/hal+json') { + if (!response.body || Object.keys(response.body).length === 0) { + response.body = JSON.parse(response.text); + } + + // and process embedded resources + response.body = utils.solveHALEmbedded(response.body); + } + + if (deferred) { + deferred.resolve( + response.body ? response.body : response.text ? response.text : '' + ); + } + done( + null, + response.body ? response.body : response.text ? response.text : '', + response.headers + ); + }; +} + +/** + * Performs a POST HTTP request + */ +HttpClient.prototype.post = function(path, options) { + options = options || {}; + var done = options.done || noop; + var self = this; + var deferred = Q.defer(); + var url = this.config.baseUrl + (path ? '/' + path : ''); + var req = request.post(url); + + var headers = options.headers || this.config.headers; + headers.Accept = headers.Accept || this.config.headers.Accept; + + var isFieldOrAttach = false; + // Buffer object is only available in node.js environement + if (typeof Buffer !== 'undefined') { + Object.keys(options.fields || {}).forEach(function(field) { + req.field(field, options.fields[field]); + isFieldOrAttach = true; + }); + (options.attachments || []).forEach(function(file, idx) { + req.attach('data_' + idx, new Buffer(file.content), file.name); + isFieldOrAttach = true; + }); + } else if (!!options.fields || !!options.attachments) { + var err = new Error( + 'Multipart request is only supported in node.js environement.' + ); + done(err); + return deferred.reject(err); + } + + if (!isFieldOrAttach) { + req.send(options.data || {}); + } + + req.set(headers).query(options.query || {}); + + req.end(end(self, done, deferred)); + return deferred.promise; +}; + +/** + * Performs a GET HTTP request + */ +HttpClient.prototype.get = function(path, options) { + var url = this.config.baseUrl + (path ? '/' + path : ''); + return this.load(url, options); +}; + +/** + * Loads a resource using http GET + */ +HttpClient.prototype.load = function(url, options) { + options = options || {}; + var done = options.done || noop; + var self = this; + var deferred = Q.defer(); + + var headers = options.headers || this.config.headers; + var accept = options.accept || headers.Accept || this.config.headers.Accept; + + var req = request + .get(url) + .set(headers) + .set('Accept', accept) + .query(options.data || {}); + + req.end(end(self, done, deferred)); + return deferred.promise; +}; + +/** + * Performs a PUT HTTP request + */ +HttpClient.prototype.put = function(path, options) { + options = options || {}; + var done = options.done || noop; + var self = this; + var deferred = Q.defer(); + var url = this.config.baseUrl + (path ? '/' + path : ''); + + var headers = options.headers || this.config.headers; + headers.Accept = headers.Accept || this.config.headers.Accept; + + var req = request + .put(url) + .set(headers) + .send(options.data || {}); + + req.end(end(self, done, deferred)); + return deferred.promise; +}; + +/** + * Performs a DELETE HTTP request + */ +HttpClient.prototype.del = function(path, options) { + options = options || {}; + var done = options.done || noop; + var self = this; + var deferred = Q.defer(); + var url = this.config.baseUrl + (path ? '/' + path : ''); + + var headers = options.headers || this.config.headers; + headers.Accept = headers.Accept || this.config.headers.Accept; + + var req = request + .del(url) + .set(headers) + .send(options.data || {}); + + req.end(end(self, done, deferred)); + return deferred.promise; +}; + +/** + * Performs a OPTIONS HTTP request + */ +HttpClient.prototype.options = function(path, options) { + options = options || {}; + var done = options.done || noop; + var self = this; + var deferred = Q.defer(); + var url = this.config.baseUrl + (path ? '/' + path : ''); + + var headers = options.headers || this.config.headers; + headers.Accept = headers.Accept || this.config.headers.Accept; + + var req = request('OPTIONS', url).set(headers); + + req.end(end(self, done, deferred)); + return deferred.promise; +}; + +module.exports = HttpClient; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/index.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f19ced6e1414034b9a5cc08b6aab7ff54d1ebd4f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/index.js @@ -0,0 +1,202 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; +var Events = require('./../events'); + +/** + * For all API client related + * @namespace CamSDK.client + */ + +/** + * For the resources implementations + * @namespace CamSDK.client.resource + */ + +/** + * Entry point of the module + * + * @class CamundaClient + * @memberof CamSDK.client + * + * @param {Object} config used to provide necessary configuration + * @param {String} [config.engine=default] false to define absolute apiUri + * @param {String} config.apiUri + * @param {String} [config.headers] Headers that should be used for all Http requests. + */ +function CamundaClient(config) { + if (!config) { + throw new Error('Needs configuration'); + } + + if (!config.apiUri) { + throw new Error('An apiUri is required'); + } + + Events.attach(this); + + // use 'default' engine + config.engine = + typeof config.engine !== 'undefined' ? config.engine : 'default'; + + // mock by default.. for now + config.mock = typeof config.mock !== 'undefined' ? config.mock : true; + + config.resources = config.resources || {}; + + this.HttpClient = config.HttpClient || CamundaClient.HttpClient; + + this.baseUrl = config.apiUri; + if (config.engine) { + this.baseUrl += this.baseUrl.slice(-1) !== '/' ? '/' : ''; + this.baseUrl += 'engine/' + config.engine; + } + + this.config = config; + + this.initialize(); +} + +/** + * [HttpClient description] + * @memberof CamSDK.client.CamundaClient + * @name HttpClient + * @type {CamSDK.client.HttpClient} + */ +CamundaClient.HttpClient = require('./http-client'); + +// provide an isolated scope +(function(proto) { + /** + * configuration storage + * @memberof CamSDK.client.CamundaClient.prototype + * @name config + * @type {Object} + */ + proto.config = {}; + + var _resources = {}; + + /** + * @memberof CamSDK.client.CamundaClient.prototype + * @name initialize + */ + proto.initialize = function() { + /* jshint sub: true */ + _resources['authorization'] = require('./resources/authorization'); + _resources['batch'] = require('./resources/batch'); + _resources['deployment'] = require('./resources/deployment'); + _resources['external-task'] = require('./resources/external-task'); + _resources['filter'] = require('./resources/filter'); + _resources['history'] = require('./resources/history'); + _resources[ + 'process-definition' + ] = require('./resources/process-definition'); + _resources['process-instance'] = require('./resources/process-instance'); + _resources['task'] = require('./resources/task'); + _resources['task-report'] = require('./resources/task-report'); + _resources['telemetry'] = require('./resources/telemetry'); + _resources['variable'] = require('./resources/variable'); + _resources['case-execution'] = require('./resources/case-execution'); + _resources['case-instance'] = require('./resources/case-instance'); + _resources['case-definition'] = require('./resources/case-definition'); + _resources['user'] = require('./resources/user'); + _resources['group'] = require('./resources/group'); + _resources['tenant'] = require('./resources/tenant'); + _resources['incident'] = require('./resources/incident'); + _resources['job-definition'] = require('./resources/job-definition'); + _resources['job'] = require('./resources/job'); + _resources['metrics'] = require('./resources/metrics'); + _resources[ + 'decision-definition' + ] = require('./resources/decision-definition'); + _resources['execution'] = require('./resources/execution'); + _resources['migration'] = require('./resources/migration'); + _resources['drd'] = require('./resources/drd'); + _resources['modification'] = require('./resources/modification'); + _resources['message'] = require('./resources/message'); + _resources['password-policy'] = require('./resources/password-policy'); + + /* jshint sub: false */ + var self = this; + + function forwardError(err) { + self.trigger('error', err); + } + + // create global HttpClient instance + this.http = new this.HttpClient({ + baseUrl: this.baseUrl, + headers: this.config.headers + }); + + // configure the client for each resources separately, + var name, conf, resConf, c; + for (name in _resources) { + conf = { + name: name, + // use the SDK config for some default values + mock: this.config.mock, + baseUrl: this.baseUrl, + headers: this.config.headers + }; + resConf = this.config.resources[name] || {}; + + for (c in resConf) { + conf[c] = resConf[c]; + } + + // instanciate a HTTP client for the resource + _resources[name].http = new this.HttpClient(conf); + + // forward request errors + _resources[name].http.on('error', forwardError); + } + }; + + /** + * Allows to get a resource from SDK by its name + * @memberof CamSDK.client.CamundaClient.prototype + * @name resource + * + * @param {String} name + * @return {CamSDK.client.AbstractClientResource} + */ + proto.resource = function(name) { + return _resources[name]; + }; +})(CamundaClient.prototype); + +module.exports = CamundaClient; + +/** + * A [universally unique identifier]{@link en.wikipedia.org/wiki/Universally_unique_identifier} + * @typedef {String} uuid + */ + +/** + * This callback is displayed as part of the Requester class. + * @callback requestCallback + * @param {?Object} error + * @param {CamSDK.AbstractClientResource|CamSDK.AbstractClientResource[]} [results] + */ + +/** + * Function who does not perform anything + * @callback noopCallback + */ diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/authorization.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/authorization.js new file mode 100644 index 0000000000000000000000000000000000000000..deba38ce67a2a0107024499924a5597d2bfddc74 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/authorization.js @@ -0,0 +1,140 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * Authorization Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Authorization = AbstractClientResource.extend(); + +/** + * API path for the process definition resource + * @type {String} + */ +Authorization.path = 'authorization'; + +/** + * Fetch a list of authorizations + * + * @param {Object} params + * @param {Object} [params.id] Authorization by the id of the authorization. + * @param {Object} [params.type] Authorization by the type of the authorization. + * @param {Object} [params.userIdIn] Authorization by a comma-separated list of userIds + * @param {Object} [params.groupIdIn] Authorization by a comma-separated list of groupIds + * @param {Object} [params.resourceType] Authorization by resource type + * @param {Object} [params.resourceId] Authorization by resource id. + * @param {Object} [params.sortBy] Sort the results lexicographically by a given criterion. + * Valid values are resourceType and resourceId. + * Must be used with the sortOrder parameter. + * @param {Object} [params.sortOrder] Sort the results in a given order. + * Values may be "asc" or "desc". + * Must be used in conjunction with the sortBy parameter. + * @param {Object} [params.firstResult] Pagination of results. + * Specifies the index of the first result to return. + * @param {Object} [params.maxResults] Pagination of results. + * Specifies the maximum number of results to return. + * @param {Function} done + */ +Authorization.list = function(params, done) { + return this.http.get(this.path, { + data: params, + done: done + }); +}; + +/** + * Retrieve a single authorization + * + * @param {uuid} authorizationId of the authorization to be requested + * @param {Function} done + */ +Authorization.get = function(authorizationId, done) { + return this.http.get(this.path + '/' + authorizationId, { + done: done + }); +}; + +/** + * Creates an authorization + * + * @param {Object} authorization is an object representation of an authorization + * @param {Function} done + */ +Authorization.create = function(authorization, done) { + return this.http.post(this.path + '/create', { + data: authorization, + done: done + }); +}; + +/** + * Update an authorization + * + * @param {Object} authorization is an object representation of an authorization + * @param {Function} done + */ +Authorization.update = function(authorization, done) { + return this.http.put(this.path + '/' + authorization.id, { + data: authorization, + done: done + }); +}; + +/** + * Save an authorization + * + * @see Authorization.create + * @see Authorization.update + * + * @param {Object} authorization is an object representation of an authorization, + * if it has an id property, the authorization will be updated, + * otherwise created + * @param {Function} done + */ +Authorization.save = function(authorization, done) { + return Authorization[authorization.id ? 'update' : 'create']( + authorization, + done + ); +}; + +/** + * Delete an authorization + * + * @param {uuid} id of the authorization to delete + * @param {Function} done + */ +Authorization.delete = function(id, done) { + return this.http.del(this.path + '/' + id, { + done: done + }); +}; + +Authorization.check = function(authorization, done) { + return this.http.get(this.path + '/check', { + data: authorization, + done: done + }); +}; + +module.exports = Authorization; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/batch.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/batch.js new file mode 100644 index 0000000000000000000000000000000000000000..b8f21e66689a9c06b02a45533b5904d41760324b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/batch.js @@ -0,0 +1,80 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * Batch Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Batch = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +Batch.path = 'batch'; + +/** + * Retrieves a single batch according to the Batch interface in the engine. + */ +Batch.get = function(id, done) { + return this.http.get(this.path + '/' + id, { + done: done + }); +}; + +Batch.suspended = function(params, done) { + return this.http.put(this.path + '/' + params.id + '/suspended', { + data: { + suspended: !!params.suspended + }, + done: done + }); +}; + +Batch.statistics = function(params, done) { + return this.http.get(this.path + '/statistics/', { + data: params, + done: done + }); +}; + +Batch.statisticsCount = function(params, done) { + return this.http.get(this.path + '/statistics/count', { + data: params, + done: done + }); +}; + +Batch.delete = function(params, done) { + var path = this.path + '/' + params.id; + + if (params.cascade) { + path += '?cascade=true'; + } + + return this.http.del(path, { + done: done + }); +}; + +module.exports = Batch; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/case-definition.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/case-definition.js new file mode 100644 index 0000000000000000000000000000000000000000..de83ab18def5476b8e5735073728b2137d95c9e6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/case-definition.js @@ -0,0 +1,128 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * No-Op callback + */ +function noop() {} + +/** + * CaseDefinition Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var CaseDefinition = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +CaseDefinition.path = 'case-definition'; + +/** + * Retrieve a single case definition + * + * @param {uuid} id of the case definition to be requested + * @param {Function} done + */ +CaseDefinition.get = function(id, done) { + return this.http.get(this.path + '/' + id, { + done: done + }); +}; + +/** + * Retrieve a single cace definition + * + * @param {String} key of the case definition to be requested + * @param {Function} done + */ +CaseDefinition.getByKey = function(key, done) { + return this.http.get(this.path + '/key/' + key, { + done: done + }); +}; + +CaseDefinition.list = function(params, done) { + return this.http.get(this.path, { + data: params, + done: done + }); +}; + +/** + * Instantiates a given case definition. + * + * @param {Object} [params] + * @param {String} [params.id] The id of the case definition to be instantiated. Must be omitted if key is provided. + * @param {String} [params.key] The key of the case definition (the latest version thereof) to be instantiated. Must be omitted if id is provided. + * @param {String} [params.variables] A JSON object containing the variables the case is to be initialized with. Each key corresponds to a variable name and each value to a variable value. + * @param {String} [params.businessKey] The business key the case instance is to be initialized with. The business key identifies the case instance in the context of the given case definition. + */ +CaseDefinition.create = function(params, done) { + var url = this.path + '/'; + + if (params.id) { + url = url + params.id; + } else { + url = url + 'key/' + params.key; + + if (params.tenantId) { + url = url + '/tenant-id/' + params.tenantId; + } + } + + return this.http.post(url + '/create', { + data: params, + done: done + }); +}; + +/** + * Retrieves the CMMN XML of this case definition. + * @param {uuid} id The id of the case definition. + * @param {Function} done + */ +CaseDefinition.xml = function(data, done) { + var path = this.path + '/' + (data.id ? data.id : 'key/' + data.key) + '/xml'; + return this.http.get(path, { + done: done || noop + }); +}; + +/** + * Instantiates a given process definition. + * + * @param {String} [id] The id of the process definition to activate or suspend. + * @param {Object} [params] + * @param {Number} [params.historyTimeToLive] New value for historyTimeToLive field of process definition. Can be null. + */ +CaseDefinition.updateHistoryTimeToLive = function(id, params, done) { + var url = this.path + '/' + id + '/history-time-to-live'; + + return this.http.put(url, { + data: params, + done: done + }); +}; + +module.exports = CaseDefinition; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/case-execution.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/case-execution.js new file mode 100644 index 0000000000000000000000000000000000000000..5c80718e0544ec8a1a156409e5ba81a9d7057a22 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/case-execution.js @@ -0,0 +1,107 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); +var utils = require('../../utils'); + +/** + * No-Op callback + */ +function noop() {} + +/** + * CaseExecution Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var CaseExecution = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +CaseExecution.path = 'case-execution'; + +CaseExecution.list = function(params, done) { + done = done || noop; + return this.http.get(this.path, { + data: params, + done: done + }); +}; + +CaseExecution.disable = function(executionId, params, done) { + return this.http.post(this.path + '/' + executionId + '/disable', { + data: params, + done: done + }); +}; + +CaseExecution.reenable = function(executionId, params, done) { + return this.http.post(this.path + '/' + executionId + '/reenable', { + data: params, + done: done + }); +}; + +CaseExecution.manualStart = function(executionId, params, done) { + return this.http.post(this.path + '/' + executionId + '/manual-start', { + data: params, + done: done + }); +}; + +CaseExecution.complete = function(executionId, params, done) { + return this.http.post(this.path + '/' + executionId + '/complete', { + data: params, + done: done + }); +}; + +/** + * Deletes a variable in the context of a given case execution. Deletion does not propagate upwards in the case execution hierarchy. + */ +CaseExecution.deleteVariable = function(data, done) { + return this.http.del( + this.path + + '/' + + data.id + + '/localVariables/' + + utils.escapeUrl(data.varId), + { + done: done + } + ); +}; + +/** + * Updates or deletes the variables in the context of an execution. + * The updates do not propagate upwards in the execution hierarchy. + * Deletion precede updates. + * So, if a variable is updated AND deleted, the updates overrides the deletion. + */ +CaseExecution.modifyVariables = function(data, done) { + return this.http.post(this.path + '/' + data.id + '/localVariables', { + data: data, + done: done + }); +}; + +module.exports = CaseExecution; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/case-instance.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/case-instance.js new file mode 100644 index 0000000000000000000000000000000000000000..dbe43d70688a06641aa47bbb029c8ef2c58a2270 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/case-instance.js @@ -0,0 +1,81 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); +var utils = require('../../utils'); + +/** + * CaseInstance Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var CaseInstance = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +CaseInstance.path = 'case-instance'; + +CaseInstance.get = function(instanceId, done) { + return this.http.get(this.path + '/' + instanceId, { + done: done + }); +}; + +CaseInstance.list = function(params, done) { + return this.http.get(this.path, { + data: params, + done: done + }); +}; + +CaseInstance.close = function(instanceId, params, done) { + return this.http.post(this.path + '/' + instanceId + '/close', { + data: params, + done: done + }); +}; + +CaseInstance.terminate = function(instanceId, params, done) { + return this.http.post(this.path + '/' + instanceId + '/terminate', { + data: params, + done: done + }); +}; + +/** + * Sets a variable of a given case instance by id. + * + * @see http://docs.camunda.org/manual/develop/reference/rest/case-instance/variables/put-variable/ + * + * @param {uuid} id + * @param {Object} params + * @param {requestCallback} done + */ +CaseInstance.setVariable = function(id, params, done) { + var url = this.path + '/' + id + '/variables/' + utils.escapeUrl(params.name); + return this.http.put(url, { + data: params, + done: done + }); +}; + +module.exports = CaseInstance; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/decision-definition.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/decision-definition.js new file mode 100644 index 0000000000000000000000000000000000000000..3594ca4f695d63c75d1478edac23357966318a88 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/decision-definition.js @@ -0,0 +1,133 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * DecisionDefinition Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var DecisionDefinition = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +DecisionDefinition.path = 'decision-definition'; + +/** + * Fetch a list of decision definitions + * @param {Object} params Query parameters as follow + * @param {String} [params.decisionDefinitionId] Filter by decision definition id. + * @param {String} [params.decisionDefinitionIdIn] Filter by decision definition ids. + * @param {String} [params.name] Filter by name. + * @param {String} [params.nameLike] Filter by names that the parameter is a substring of. + * @param {String} [params.deploymentId] Filter by the deployment the id belongs to. + * @param {String} [params.key] Filter by key, i.e. the id in the DMN 1.0 XML. Exact match. + * @param {String} [params.keyLike] Filter by keys that the parameter is a substring of. + * @param {String} [params.category] Filter by category. Exact match. + * @param {String} [params.categoryLike] Filter by categories that the parameter is a substring of. + * @param {String} [params.version] Filter by version. + * @param {String} [params.latestVersion] Only include those decision definitions that are latest versions. + * Values may be "true" or "false". + * @param {String} [params.resourceName] Filter by the name of the decision definition resource. Exact match. + * @param {String} [params.resourceNameLike] Filter by names of those decision definition resources that the parameter is a substring of. + * + * @param {String} [params.sortBy] Sort the results lexicographically by a given criterion. + * Valid values are category, "key", "id", "name", "version" and "deploymentId". + * Must be used in conjunction with the "sortOrder" parameter. + * + * @param {String} [params.sortOrder] Sort the results in a given order. + * Values may be asc for ascending "order" or "desc" for descending order. + * Must be used in conjunction with the sortBy parameter. + * + * @param {Integer} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {Integer} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. + * Will return less results, if there are no more results left. + * @param {Function} done + */ +DecisionDefinition.list = function(params, done) { + return this.http.get(this.path, { + data: params, + done: done + }); +}; + +/** + * Retrieves a single decision definition according to the DecisionDefinition interface in the engine. + * @param {uuid} id The id of the decision definition to be retrieved. + * @param {Function} done + */ +DecisionDefinition.get = function(id, done) { + return this.http.get(this.path + '/' + id, { + done: done + }); +}; + +/** + * Retrieves the DMN 1.0 XML of this decision definition. + * @param {uuid} id The id of the decision definition. + * @param {Function} done + */ +DecisionDefinition.getXml = function(id, done) { + return this.http.get(this.path + '/' + id + '/xml', { + done: done + }); +}; + +/** + * Evaluates a given decision. + * + * @param {Object} [params] + * @param {String} [params.id] The id of the decision definition to be evaluated. Must be omitted if key is provided. + * @param {String} [params.key] The key of the decision definition (the latest version thereof) to be evaluated. Must be omitted if id is provided. + * @param {String} [params.variables] A JSON object containing the input variables of the decision. Each key corresponds to a variable name and each value to a variable value. + */ +DecisionDefinition.evaluate = function(params, done) { + return this.http.post( + this.path + + '/' + + (params.id ? params.id : 'key/' + params.key) + + '/evaluate', + { + data: params, + done: done + } + ); +}; + +/** + * Instantiates a given process definition. + * + * @param {String} [id] The id of the process definition to activate or suspend. + * @param {Object} [params] + * @param {Number} [params.historyTimeToLive] New value for historyTimeToLive field of process definition. Can be null. + */ +DecisionDefinition.updateHistoryTimeToLive = function(id, params, done) { + var url = this.path + '/' + id + '/history-time-to-live'; + + return this.http.put(url, { + data: params, + done: done + }); +}; + +module.exports = DecisionDefinition; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/deployment.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/deployment.js new file mode 100644 index 0000000000000000000000000000000000000000..7bc44ffdd1f387036cc6e0144bba515a786ce684 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/deployment.js @@ -0,0 +1,206 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * Deployment Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Deployment = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +Deployment.path = 'deployment'; + +/** + * Create a deployment + * @param {Object} options + * + * @param {Array} options.files + * + * @param {String} options.deploymentName + * @param {String} [options.deploymentSource] + * @param {String} [options.enableDuplicateFiltering] + * @param {String} [options.deployChangedOnly] + * @param {String} [options.tenantId] + * @param {Function} done + */ +Deployment.create = function(options, done) { + var fields = { + 'deployment-name': options.deploymentName + }; + + var files = Array.isArray(options.files) ? options.files : [options.files]; + + if (options.deploymentSource) { + fields['deployment-source'] = options.deploymentSource; + } + + if (options.enableDuplicateFiltering) { + fields['enable-duplicate-filtering'] = 'true'; + } + + if (options.deployChangedOnly) { + fields['deploy-changed-only'] = 'true'; + } + + if (options.tenantId) { + fields['tenant-id'] = options.tenantId; + } + + return this.http.post(this.path + '/create', { + data: {}, + fields: fields, + attachments: files, + done: done + }); +}; + +/** + * Deletes a deployment + * + * @param {String} id + * + * @param {Object} options + * + * @param {Boolean} [options.cascade] + * @param {Boolean} [options.skipCustomListeners] + * + * @param {Function} done + */ +Deployment.delete = function(id, options, done) { + var path = this.path + '/' + id; + + if (options) { + var queryParams = []; + for (var key in options) { + var value = options[key]; + queryParams.push(key + '=' + value); + } + + if (queryParams.length) { + path += '?' + queryParams.join('&'); + } + } + + return this.http.del(path, { + done: done + }); +}; + +/** + * Lists the deployments + * @param {Object} params An object containing listing options. + * @param {uuid} [params.id] Filter by deployment id. + * @param {String} [params.name] Filter by the deployment name. Exact match. + * @param {String} [params.nameLike] Filter by the deployment name that the parameter is a + * substring of. The parameter can include the wildcard % + * to express like-strategy such as: starts with (%name), + * ends with (name%) or contains (%name%). + * @param {String} [params.after] Restricts to all deployments after the given date. + * The date must have the format yyyy-MM-dd'T'HH:mm:ss, + * e.g., 2013-01-23T14:42:45 + * @param {String} [params.before] Restricts to all deployments before the given date. + * The date must have the format yyyy-MM-dd'T'HH:mm:ss, + * e.g., 2013-01-23T14:42:45 + * @param {String} [params.sortBy] Sort the results lexicographically by a given criterion. + * Valid values are id, name and deploymentTime. Must be + * used in conjunction with the sortOrder parameter. + * @param {String} [params.sortOrder] Sort the results in a given order. Values may be asc for + * ascending order or desc for descending order. Must be + * used in conjunction with the sortBy parameter. + * @param {Integer} [params.firstResult] Pagination of results. Specifies the index of the first + * result to return. + * @param {Integer} [params.maxResults] Pagination of results. Specifies the maximum number of + * results to return. Will return less results if there are + * no more results left. + * @param {Function} done + */ +Deployment.list = function() { + return AbstractClientResource.list.apply(this, arguments); +}; + +/** + * Returns information about a deployment resources for the given deployment. + */ +Deployment.get = function(id, done) { + return this.http.get(this.path + '/' + id, { + done: done + }); +}; + +/** + * Returns a list of deployment resources for the given deployment. + */ +Deployment.getResources = function(id, done) { + return this.http.get(this.path + '/' + id + '/resources', { + done: done + }); +}; + +/** + * Returns a deployment resource for the given deployment and resource id. + */ +Deployment.getResource = function(deploymentId, resourceId, done) { + return this.http.get( + this.path + '/' + deploymentId + '/resources/' + resourceId, + { + done: done + } + ); +}; + +/** + * Returns the binary content of a single deployment resource for the given deployment. + */ +Deployment.getResourceData = function(deploymentId, resourceId, done) { + return this.http.get( + this.path + '/' + deploymentId + '/resources/' + resourceId + '/data', + { + accept: '*/*', + done: done + } + ); +}; + +/** + * Redeploy a deployment + + * @param {Object} options + * @param {String} options.id + * @param {Array} [options.resourceIds] + * @param {Array} [options.resourceNames] + * @param {Function} done + */ +Deployment.redeploy = function(options, done) { + var id = options.id; + delete options.id; + + return this.http.post(this.path + '/' + id + '/redeploy', { + data: options, + done: done || function() {} + }); +}; + +module.exports = Deployment; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/drd.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/drd.js new file mode 100644 index 0000000000000000000000000000000000000000..6f579152b10e44a2b3daeb38aaf148ebc36410f3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/drd.js @@ -0,0 +1,201 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('../abstract-client-resource'); +var utils = require('../../utils'); + +/** + * DRD (Decision Requirements Definition) Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var DRD = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +DRD.path = 'decision-requirements-definition'; + +/** + * Fetch a count of DRD's + * @param {Object} params Query parameters as follow + * @param {String} [params.decisionDefinitionId] Filter by decision definition id. + * @param {String} [params.decisionDefinitionIdIn] Filter by decision definition ids. + * @param {String} [params.name] Filter by name. + * @param {String} [params.nameLike] Filter by names that the parameter is a substring of. + * @param {String} [params.deploymentId] Filter by the deployment the id belongs to. + * @param {String} [params.key] Filter by key, i.e. the id in the DMN 1.0 XML. Exact match. + * @param {String} [params.keyLike] Filter by keys that the parameter is a substring of. + * @param {String} [params.category] Filter by category. Exact match. + * @param {String} [params.categoryLike] Filter by categories that the parameter is a substring of. + * @param {String} [params.version] Filter by version. + * @param {String} [params.latestVersion] Only include those decision definitions that are latest versions. + * Values may be "true" or "false". + * @param {String} [params.resourceName] Filter by the name of the decision definition resource. Exact match. + * @param {String} [params.resourceNameLike] Filter by names of those decision definition resources that the parameter is a substring of. + * + * @param {String} [params.tenantIdInIdLn] Filter by a comma-separated list of tenant ids. A decision requirements definition + * must have one of the given tenant ids. + * + * @param {Boolean} [params.withoutTenantId] Only include decision requirements definitions which belongs to no tenant. + * Value may only be true, as false is the default behavior. + * + * @param {String} [params.includeDecisionRequirementsDefinitionsWithoutTenantId] Include decision requirements definitions which belongs to no tenant. + * Can be used in combination with tenantIdIn. Value may only be true, as false is the default behavior. + * @param {Function} done + */ +DRD.count = function(params, done) { + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(this.path + '/count', { + data: params, + done: done + }); +}; + +/** + * Fetch a list of decision definitions + * @param {Object} params Query parameters as follow + * @param {String} [params.decisionDefinitionId] Filter by decision definition id. + * @param {String} [params.decisionDefinitionIdIn] Filter by decision definition ids. + * @param {String} [params.name] Filter by name. + * @param {String} [params.nameLike] Filter by names that the parameter is a substring of. + * @param {String} [params.deploymentId] Filter by the deployment the id belongs to. + * @param {String} [params.key] Filter by key, i.e. the id in the DMN 1.0 XML. Exact match. + * @param {String} [params.keyLike] Filter by keys that the parameter is a substring of. + * @param {String} [params.category] Filter by category. Exact match. + * @param {String} [params.categoryLike] Filter by categories that the parameter is a substring of. + * @param {String} [params.version] Filter by version. + * @param {String} [params.latestVersion] Only include those decision definitions that are latest versions. + * Values may be "true" or "false". + * @param {String} [params.resourceName] Filter by the name of the decision definition resource. Exact match. + * @param {String} [params.resourceNameLike] Filter by names of those decision definition resources that the parameter is a substring of. + * + * @param {String} [params.tenantIdInIdLn] Filter by a comma-separated list of tenant ids. A decision requirements definition + * must have one of the given tenant ids. + * + * @param {Boolean} [params.withoutTenantId] Only include decision requirements definitions which belongs to no tenant. + * Value may only be true, as false is the default behavior. + * + * @param {String} [params.includeDecisionRequirementsDefinitionsWithoutTenantId] Include decision requirements definitions which belongs to no tenant. + * Can be used in combination with tenantIdIn. Value may only be true, as false is the default behavior. + * + * @param {String} [params.sortBy] Sort the results lexicographically by a given criterion. + * Valid values are category, "key", "id", "name", "version" and "deploymentId". + * Must be used in conjunction with the "sortOrder" parameter. + * + * @param {String} [params.sortOrder] Sort the results in a given order. + * Values may be asc for ascending "order" or "desc" for descending order. + * Must be used in conjunction with the sortBy parameter. + * + * @param {Integer} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {Integer} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. + * Will return less results, if there are no more results left. + * @param {Function} done + */ +DRD.list = function(params, done) { + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(this.path, { + data: params, + done: done + }); +}; + +function createIdUrl(path, id) { + return path + '/' + utils.escapeUrl(id); +} + +/** + * Retrieves a single decision requirements definition. + * @param {uuid} id The id of the decision definition to be retrieved. + * @param {Function} done + */ +DRD.get = function(id, done) { + return this.http.get(createIdUrl(this.path, id), { + done: done + }); +}; + +function createKeyTenantUrl(path, key, tenantId) { + var url = path + '/key/' + utils.escapeUrl(key); + + if (typeof tenantId !== 'function') { + url += '/tenant-id/' + utils.escapeUrl(tenantId); + } + + return url; +} + +/** + * Retrieves a single decision requirements definition. + * @param {string} key The key of the decision requirements definition (the latest version thereof) to be retrieved. + * @param {uuid} [tenantId] The id of the tenant to which the decision requirements definition belongs to. + * @param {Function} done + */ +DRD.getByKey = function(key, tenantId, done) { + var url = createKeyTenantUrl(this.path, key, tenantId); + + if (typeof tenantId === 'function') { + done = tenantId; + } + + return this.http.get(url, { + done: done + }); +}; + +/** + * Retrieves the DMN XML of this decision requirements definition. + * @param {uuid} id The id of the decision definition to be retrieved. + * @param {Function} done + */ +DRD.getXML = function(id, done) { + return this.http.get(createIdUrl(this.path, id) + '/xml', { + done: done + }); +}; + +/** + * Retrieves the DMN XML of this decision requirements definition. + * @param {string} key The key of the decision requirements definition (the latest version thereof) to be retrieved. + * @param {uuid} [tenantId] The id of the tenant to which the decision requirements definition belongs to. + * @param {Function} done + */ +DRD.getXMLByKey = function(key, tenantId, done) { + var url = createKeyTenantUrl(this.path, key, tenantId) + '/xml'; + + if (typeof tenantId === 'function') { + done = tenantId; + } + + return this.http.get(url, { + done: done + }); +}; + +module.exports = DRD; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/execution.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/execution.js new file mode 100644 index 0000000000000000000000000000000000000000..69ca2476c68243994a7e6d582b9c7b8431a7cad6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/execution.js @@ -0,0 +1,66 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); +var utils = require('../../utils'); + +/** + * Execution Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Execution = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +Execution.path = 'execution'; + +/** + * Deletes a variable in the context of a given execution. Deletion does not propagate upwards in the execution hierarchy. + */ +Execution.deleteVariable = function(data, done) { + return this.http.del( + this.path + + '/' + + data.id + + '/localVariables/' + + utils.escapeUrl(data.varId), + { + done: done + } + ); +}; + +/** + * Updates or deletes the variables in the context of an execution. + * The updates do not propagate upwards in the execution hierarchy. + * Updates precede deletions. + * So, if a variable is updated AND deleted, the deletion overrides the update. + */ +Execution.modifyVariables = function(data, done) { + return this.http.post(this.path + '/' + data.id + '/localVariables', { + data: data, + done: done + }); +}; + +module.exports = Execution; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/external-task.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/external-task.js new file mode 100644 index 0000000000000000000000000000000000000000..87f1a3e60a191684c142b2389f4238bac291c115 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/external-task.js @@ -0,0 +1,226 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * ExternalTask Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var ExternalTask = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +ExternalTask.path = 'external-task'; + +/** + * Retrieves a single external task corresponding to the ExternalTask interface in the engine. + * + * @param {Object} [params] + * @param {String} [params.id] The id of the external task to be retrieved. + */ +ExternalTask.get = function(params, done) { + return this.http.get(this.path + '/' + params.id, { + data: params, + done: done + }); +}; + +/** + * Query for external tasks that fulfill given parameters in the form of a json object. This method is slightly more + * powerful than the GET query because it allows to specify a hierarchical result sorting. + * + * @param {Object} [params] + * @param {String} [params.externalTaskId] Filter by an external task's id. + * @param {String} [params.topicName] Filter by an external task topic. + * @param {String} [params.workerId] Filter by the id of the worker that the task was most recently locked by. + * @param {String} [params.locked] Only include external tasks that are currently locked (i.e. they have a lock time and it has not expired). Value may only be true, as false matches any external task. + * @param {String} [params.notLocked] Only include external tasks that are currently not locked (i.e. they have no lock or it has expired). Value may only be true, as false matches any external task. + * @param {String} [params.withRetriesLeft] Only include external tasks that have a positive (> 0) number of retries (or null). Value may only be true, as false matches any external task. + * @param {String} [params.noRetriesLeft] Only include external tasks that have 0 retries. Value may only be true, as false matches any external task. + * @param {String} [params.lockExpirationAfter] Restrict to external tasks that have a lock that expires after a given date. The date must have the format yyyy-MM-dd'T'HH:mm:ss, e.g., 2013-01-23T14:42:45. + * @param {String} [params.lockExpirationBefore] Restrict to external tasks that have a lock that expires before a given date. The date must have the format yyyy-MM-dd'T'HH:mm:ss, e.g., 2013-01-23T14:42:45. + * @param {String} [params.activityId] Filter by the id of the activity that an external task is created for. + * @param {String} [params.executionId] Filter by the id of the execution that an external task belongs to. + * @param {String} [params.processInstanceId] Filter by the id of the process instance that an external task belongs to. + * @param {String} [params.processDefinitionId] Filter by the id of the process definition that an external task belongs to. + * @param {String} [params.active] Only include active tasks. Value may only be true, as false matches any external task. + * @param {String} [params.suspended] Only include suspended tasks. Value may only be true, as false matches any external task. + * @param {String} [params.sorting] A JSON array of criteria to sort the result by. Each element of the array is a JSON object that specifies one ordering. The position in the array identifies the rank of an ordering, i.e. whether it is primary, secondary, etc. The ordering objects have the following properties: + * - sortBy Mandatory. Sort the results lexicographically by a given criterion. Valid values are id, lockExpirationTime, processInstanceId, processDefinitionId, and processDefinitionKey. + * - sortOrder Mandatory. Sort the results in a given order. Values may be asc for ascending order or desc for descending order. + * @param {String} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {String} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + */ +ExternalTask.list = function(params, done) { + var path = this.path + '/'; + + // those parameters have to be passed in the query and not body + path += '?firstResult=' + (params.firstResult || 0); + path += '&maxResults=' + (params.maxResults || 15); + + return this.http.post(path, { + data: params, + done: done + }); +}; + +/** + * Query for the number of external tasks that fulfill given parameters. Takes the same parameters as the get external tasks method. + * + * @param {Object} [params] + * @param {String} [params.externalTaskId] Filter by an external task's id. + * @param {String} [params.topicName] Filter by an external task topic. + * @param {String} [params.workerId] Filter by the id of the worker that the task was most recently locked by. + * @param {String} [params.locked] Only include external tasks that are currently locked (i.e. they have a lock time and it has not expired). Value may only be true, as false matches any external task. + * @param {String} [params.notLocked] Only include external tasks that are currently not locked (i.e. they have no lock or it has expired). Value may only be true, as false matches any external task. + * @param {String} [params.withRetriesLeft] Only include external tasks that have a positive (> 0) number of retries (or null). Value may only be true, as false matches any external task. + * @param {String} [params.noRetriesLeft] Only include external tasks that have 0 retries. Value may only be true, as false matches any external task. + * @param {String} [params.lockExpirationAfter] Restrict to external tasks that have a lock that expires after a given date. The date must have the format yyyy-MM-dd'T'HH:mm:ss, e.g., 2013-01-23T14:42:45. + * @param {String} [params.lockExpirationBefore] Restrict to external tasks that have a lock that expires before a given date. The date must have the format yyyy-MM-dd'T'HH:mm:ss, e.g., 2013-01-23T14:42:45. + * @param {String} [params.activityId] Filter by the id of the activity that an external task is created for. + * @param {String} [params.executionId] Filter by the id of the execution that an external task belongs to. + * @param {String} [params.processInstanceId] Filter by the id of the process instance that an external task belongs to. + * @param {String} [params.processDefinitionId] Filter by the id of the process definition that an external task belongs to. + * @param {String} [params.active] Only include active tasks. Value may only be true, as false matches any external task. + * @param {String} [params.suspended] Only include suspended tasks. Value may only be true, as false matches any external task. + */ +ExternalTask.count = function(params, done) { + return this.http.post(this.path + '/count', { + data: params, + done: done + }); +}; + +/** + * Query for the number of external tasks that fulfill given parameters. Takes the same parameters as the get external tasks method. + * + * @param {Object} [params] + * @param {String} [params.workerId] Mandatory. The id of the worker on which behalf tasks are fetched. The returned tasks are locked for that worker and can only be completed when providing the same worker id. + * @param {String} [params.maxTasks] Mandatory. The maximum number of tasks to return. + * @param {String} [params.topics] A JSON array of topic objects for which external tasks should be fetched. The returned tasks may be arbitrarily distributed among these topics. + * + * Each topic object has the following properties: + * Name Description + * topicName Mandatory. The topic's name. + * lockDuration Mandatory. The duration to lock the external tasks for in milliseconds. + * variables A JSON array of String values that represent variable names. For each result task belonging to this topic, the given variables are returned as well if they are accessible from the external task's execution. + */ +ExternalTask.fetchAndLock = function(params, done) { + return this.http.post(this.path + '/fetchAndLock', { + data: params, + done: done + }); +}; + +/** + * Complete an external task and update process variables. + * + * @param {Object} [params] + * @param {String} [params.id] The id of the task to complete. + * @param {String} [params.workerId] The id of the worker that completes the task. Must match the id of the worker who has most recently locked the task. + * @param {String} [params.variables] A JSON object containing variable key-value pairs. + * + * Each key is a variable name and each value a JSON variable value object with the following properties: + * Name Description + * value The variable's value. For variables of type Object, the serialized value has to be submitted as a String value. + * For variables of type File the value has to be submitted as Base64 encoded string. + * type The value type of the variable. + * valueInfo A JSON object containing additional, value-type-dependent properties. + * For serialized variables of type Object, the following properties can be provided: + * - objectTypeName: A string representation of the object's type name. + * - serializationDataFormat: The serialization format used to store the variable. + * For serialized variables of type File, the following properties can be provided: + * - filename: The name of the file. This is not the variable name but the name that will be used when downloading the file again. + * - mimetype: The mime type of the file that is being uploaded. + * - encoding: The encoding of the file that is being uploaded. + */ +ExternalTask.complete = function(params, done) { + return this.http.post(this.path + '/' + params.id + '/complete', { + data: params, + done: done + }); +}; + +/** + * Report a failure to execute an external task. A number of retries and a timeout until + * the task can be retried can be specified. If retries are set to 0, an incident for this + * task is created. + * + * @param {Object} [params] + * @param {String} [params.id] The id of the external task to report a failure for. + * @param {String} [params.workerId] The id of the worker that reports the failure. Must match the id of the worker who has most recently locked the task. + * @param {String} [params.errorMessage] An message indicating the reason of the failure. + * @param {String} [params.retries] A number of how often the task should be retried. Must be >= 0. If this is 0, an incident is created and the task cannot be fetched anymore unless the retries are increased again. The incident's message is set to the errorMessage parameter. + * @param {String} [params.retryTimeout] A timeout in milliseconds before the external task becomes available again for fetching. Must be >= 0. + */ +ExternalTask.failure = function(params, done) { + return this.http.post(this.path + '/' + params.id + '/failure', { + data: params, + done: done + }); +}; + +/** + * Unlock an external task. Clears the task’s lock expiration time and worker id. + * + * @param {Object} [params] + * @param {String} [params.id] The id of the external task to unlock. + */ +ExternalTask.unlock = function(params, done) { + return this.http.post(this.path + '/' + params.id + '/unlock', { + data: params, + done: done + }); +}; + +/** + * Set the number of retries left to execute an external task. If retries are set to 0, an incident is created. + * + * @param {Object} [params] + * @param {String} [params.id] The id of the external task to unlock. + * @param {String} [params.retries] The number of retries to set for the external task. Must be >= 0. If this is 0, an incident is created and the task cannot be fetched anymore unless the retries are increased again. + */ +ExternalTask.retries = function(params, done) { + return this.http.put(this.path + '/' + params.id + '/retries', { + data: params, + done: done + }); +}; + +/** + * Set the number of retries left to execute an external task asynchronously. If retries are set to 0, an incident is created. + * + * @see https://docs.camunda.org/manual/latest/reference/rest/external-task/post-retries-async/ + * + * @param {Object} params + * @param {requestCallback} done + */ +ExternalTask.retriesAsync = function(params, done) { + return this.http.post(this.path + '/retries-async', { + data: params, + done: done + }); +}; + +module.exports = ExternalTask; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/filter.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/filter.js new file mode 100644 index 0000000000000000000000000000000000000000..fe81bb4baf64e0618689c18fdd7cf15c895b85f0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/filter.js @@ -0,0 +1,174 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * Filter Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Filter = AbstractClientResource.extend(); + +/** + * API path for the filter resource + * @type {String} + */ +Filter.path = 'filter'; + +/** + * Retrieve a single filter + * + * @param {uuid} filterId of the filter to be requested + * @param {Function} done + */ +Filter.get = function(filterId, done) { + return this.http.get(this.path + '/' + filterId, { + done: done + }); +}; + +/** + * Retrieve some filters + * + * @param {Object} data + * @param {Integer} [data.firstResult] + * @param {Integer} [data.maxResults] + * @param {String} [data.sortBy] + * @param {String} [data.sortOrder] + * @param {Bool} [data.itemCount] + * @param {Function} done + */ +Filter.list = function(data, done) { + return this.http.get(this.path, { + data: data, + done: done + }); +}; + +/** + * Get the tasks result of filter + * + * @param {(Object.|uuid)} data uuid of a filter or parameters + * @param {uuid} [data.id] uuid of the filter to be requested + * @param {Integer} [data.firstResult] + * @param {Integer} [data.maxResults] + * @param {String} [data.sortBy] + * @param {String} [data.sortOrder] + * @param {Function} done + */ +Filter.getTasks = function(data, done) { + var path = this.path + '/'; + + if (typeof data === 'string') { + path = path + data + '/list'; + data = {}; + } else { + path = path + data.id + '/list'; + delete data.id; + } + + // those parameters have to be passed in the query and not body + path += '?firstResult=' + (data.firstResult || 0); + path += '&maxResults=' + (data.maxResults || 15); + + return this.http.post(path, { + data: data, + done: done + }); +}; + +/** + * Creates a filter + * + * @param {Object} filter is an object representation of a filter + * @param {Function} done + */ +Filter.create = function(filter, done) { + return this.http.post(this.path + '/create', { + data: filter, + done: done + }); +}; + +/** + * Update a filter + * + * @param {Object} filter is an object representation of a filter + * @param {Function} done + */ +Filter.update = function(filter, done) { + return this.http.put(this.path + '/' + filter.id, { + data: filter, + done: done + }); +}; + +/** + * Save a filter + * + * @see Filter.create + * @see Filter.update + * + * @param {Object} filter is an object representation of a filter, if it has + * an id property, the filter will be updated, otherwise created + * @param {Function} done + */ +Filter.save = function(filter, done) { + return Filter[filter.id ? 'update' : 'create'](filter, done); +}; + +/** + * Delete a filter + * + * @param {uuid} id of the filter to delete + * @param {Function} done + */ +Filter.delete = function(id, done) { + return this.http.del(this.path + '/' + id, { + done: done + }); +}; + +/** + * Performs an authorizations lookup on the resource or entity + * + * @param {uuid} [id] of the filter to get authorizations for + * @param {Function} done + */ +Filter.authorizations = function(id, done) { + if (typeof id === 'function') { + return this.http.options(this.path, { + done: id, + headers: { + Accept: 'application/json' + } + }); + } + + return this.http.options(this.path + '/' + id, { + done: done, + headers: { + Accept: 'application/json' + } + }); +}; + +module.exports = Filter; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/group.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/group.js new file mode 100644 index 0000000000000000000000000000000000000000..e23fa2a026b697c4300f3005ec6343551197b2c0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/group.js @@ -0,0 +1,238 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); +var utils = require('../../utils'); + +/** + * No-Op callback + */ +function noop() {} + +/** + * Group Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Group = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +Group.path = 'group'; + +/** + * Check resource access + * @param {Object} options + * @param {String} options.id + * @param {Function} done + */ +Group.options = function(options, done) { + var id; + + if (typeof options === 'function') { + done = options; + id = ''; + } else { + id = typeof options === 'string' ? options : options.id; + if (id === undefined) { + id = ''; + } + } + + return this.http.options(this.path + '/' + utils.escapeUrl(id), { + done: done || noop, + headers: { + Accept: 'application/json' + } + }); +}; + +/** + * Creates a group + * + * @param {Object} group is an object representation of a group + * @param {String} group.id + * @param {String} group.name + * @param {String} group.type + * @param {Function} done + */ +Group.create = function(options, done) { + return this.http.post(this.path + '/create', { + data: options, + done: done || noop + }); +}; + +/** + * Query for groups using a list of parameters and retrieves the count + * + * @param {String} [options.id] Filter by the id of the group. + * @param {String} [options.name] Filter by the name of the group. + * @param {String} [options.nameLike] Filter by the name that the parameter is a substring of. + * @param {String} [options.type] Filter by the type of the group. + * @param {String} [options.member] Only retrieve groups where the given user id is a member of. + * @param {Function} done + */ +Group.count = function(options, done) { + if (typeof options === 'function') { + done = options; + options = {}; + } else { + options = options || {}; + } + + return this.http.get(this.path + '/count', { + data: options, + done: done || noop + }); +}; + +/** + * Retrieves a single group + * + * @param {String} [options.id] The id of the group, can be a property (id) of an object + * @param {Function} done + */ +Group.get = function(options, done) { + var id = typeof options === 'string' ? options : options.id; + + return this.http.get(this.path + '/' + utils.escapeUrl(id), { + data: options, + done: done || noop + }); +}; + +/** + * Query for a list of groups using a list of parameters. + * The size of the result set can be retrieved by using the get groups count method + * + * @param {String} [options.id] Filter by the id of the group. + * @param {String} [options.idIn] Filter by multiple ids. + * @param {String} [options.name] Filter by the name of the group. + * @param {String} [options.nameLike] Filter by the name that the parameter is a substring of. + * @param {String} [options.type] Filter by the type of the group. + * @param {String} [options.member] Only retrieve groups where the given user id is a member of. + * @param {String} [options.sortBy] Sort the results lexicographically by a given criterion. + * Valid values are id, name and type. + * Must be used in conjunction with the sortOrder parameter. + * @param {String} [options.sortOrder] Sort the results in a given order. + * Values may be asc for ascending order or desc for descending order. + * Must be used in conjunction with the sortBy parameter. + * @param {String} [options.firstResult] Pagination of results. + * Specifies the index of the first result to return. + * @param {String} [options.maxResults] Pagination of results. + * Specifies the maximum number of results to return. + * Will return less results if there are no more results left. + * + * @param {Function} done + */ +Group.list = function(options, done) { + if (typeof options === 'function') { + done = options; + options = {}; + } else { + options = options || {}; + } + + var query = {}; + + if (options.maxResults) { + query.maxResults = options.maxResults; + query.firstResult = options.firstResult; + } + + return this.http.post(this.path, { + data: options, + query: query, + done: done || noop + }); +}; + +/** + * Add a memeber to a Group + * + * @param {String} [options.id] The id of the group + * @param {String} [options.userId] The id of user to add to the group + * @param {Function} done + */ +Group.createMember = function(options, done) { + return this.http.put( + this.path + + '/' + + utils.escapeUrl(options.id) + + '/members/' + + utils.escapeUrl(options.userId), + { + data: options, + done: done || noop + } + ); +}; + +/** + * Removes a memeber of a Group + * + * @param {String} [options.id] The id of the group + * @param {String} [options.userId] The id of user to add to the group + * @param {Function} done + */ +Group.deleteMember = function(options, done) { + return this.http.del( + this.path + + '/' + + utils.escapeUrl(options.id) + + '/members/' + + utils.escapeUrl(options.userId), + { + data: options, + done: done || noop + } + ); +}; + +/** + * Update a group + * + * @param {Object} group is an object representation of a group + * @param {Function} done + */ +Group.update = function(options, done) { + return this.http.put(this.path + '/' + utils.escapeUrl(options.id), { + data: options, + done: done || noop + }); +}; + +/** + * Delete a group + * + * @param {Object} group is an object representation of a group + * @param {Function} done + */ +Group.delete = function(options, done) { + return this.http.del(this.path + '/' + utils.escapeUrl(options.id), { + data: options, + done: done || noop + }); +}; + +module.exports = Group; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/history.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/history.js new file mode 100644 index 0000000000000000000000000000000000000000..37c528f0191f3f374e104b7baf0072571bfb949d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/history.js @@ -0,0 +1,1302 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('../abstract-client-resource'); +var helpers = require('../helpers'); + +/** + * History Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var History = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +History.path = 'history'; + +/** + * Queries for the number of user operation log entries that fulfill the given parameters + * + * @param {Object} [params] + * @param {String} [params.processDefinitionId] Filter by process definition id. + * @param {String} [params.processDefinitionKey] Filter by process definition key. + * @param {String} [params.processInstanceId] Filter by process instance id. + * @param {String} [params.executionId] Filter by execution id. + * @param {String} [params.caseDefinitionId] Filter by case definition id. + * @param {String} [params.caseInstanceId] Filter by case instance id. + * @param {String} [params.caseExecutionId] Filter by case execution id. + * @param {String} [params.taskId] Only include operations on this task. + * @param {String} [params.userId] Only include operations of this user. + * @param {String} [params.operationId] Filter by the id of the operation. This allows fetching of multiple entries which are part of a composite operation. + * @param {String} [params.operationType] Filter by the type of the operation like Claim or Delegate. + * @param {String} [params.entityType] Filter by the type of the entity that was affected by this operation, possible values are Task, Attachment or IdentityLink. + * @param {String} [params.property] Only include operations that changed this property, e.g. owner or assignee + * @param {String} [params.afterTimestamp] Restrict to entries that were created after the given timestamp. The timestamp must have the format yyyy-MM-dd'T'HH:mm:ss, e.g. 2014-02-25T14:58:37 + * @param {String} [params.beforeTimestamp] Restrict to entries that were created before the given timestamp. The timestamp must have the format yyyy-MM-dd'T'HH:mm:ss, e.g. 2014-02-25T14:58:37 + * @param {String} [params.sortBy] Sort the results by a given criterion. At the moment the query only supports sorting based on the timestamp. + * @param {String} [params.sortOrder] Sort the results in a given order. Values may be asc for ascending order or desc for descending order. Must be used in conjunction with the sortBy parameter. + * @param {Number} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {Number} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + * @param {Function} done + */ +History.userOperationCount = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.get(this.path + '/user-operation/count', { + data: params, + done: done + }); +}; + +/** + * Queries for user operation log entries that fulfill the given parameters + * This method takes the same parameters as `History.userOperationCount`. + */ +History.userOperation = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.get(this.path + '/user-operation', { + data: params, + done: done + }); +}; + +/** + * Set an annotation for auditing reasons. + * + * @param {Object} [params] + * @param {String} [params.id] Operation ID to set the Annotation + * @param {String} [params.annotation] An arbitrary text annotation set by a user for auditing reasons. + * @param {Function} done + */ + +History.setUserOperationAnnotation = function(params, done) { + return this.http.put( + this.path + '/user-operation/' + params.id + '/set-annotation', + { + data: params, + done: done + } + ); +}; + +/** + * Clear the annotation which was previously set for auditing reasons. + * + * @param {String} [id] The operation id of the operation log to be updated. + * @param {Function} done + */ + +History.clearUserOperationAnnotation = function(id, done) { + return this.http.put( + this.path + '/user-operation/' + id + '/clear-annotation', + { + done: done + } + ); +}; + +/** + * Query for historic process instances that fulfill the given parameters. + * + * @param {Object} [params] + * @param {uuid} [params.processInstanceId] Filter by process instance id. + * @param {uuid[]} [params.processInstanceIds] Filter by process instance ids. + * Must be a json array process instance ids. + * @param {String} [params.processInstanceBusinessKey] Filter by process instance business key. + * @param {String} [params.processInstanceBusinessKeyLike] Filter by process instance business key that the parameter is a substring of. + * @param {uuid} [params.superProcessInstanceId] Restrict query to all process instances that are sub process instances of the given process instance. + * Takes a process instance id. + * @param {uuid} [params.subProcessInstanceId] Restrict query to one process instance that has a sub process instance with the given id. + * @param {uuid} [params.superCaseInstanceId] Restrict query to all process instances that are sub process instances of the given case instance. + * Takes a case instance id. + * @param {uuid} [params.subCaseInstanceId] Restrict query to one process instance that has a sub case instance with the given id. + * @param {uuid} [params.caseInstanceId] Restrict query to all process instances that are sub process instances of the given case instance. + * Takes a case instance id. + * @param {uuid} [params.processDefinitionId] Filter by the process definition the instances run on. + * @param {String} [params.processDefinitionKey] Filter by the key of the process definition the instances run on. + * @param {String[]} [params.processDefinitionKeyNotIn] Exclude instances that belong to a set of process definitions. + * Must be a json array of process definition keys. + * @param {String} [params.processDefinitionName] Filter by the name of the process definition the instances run on. + * @param {String} [params.processDefinitionNameLike] Filter by process definition names that the parameter is a substring of. + * @param {Boolean} [params.finished] Only include finished process instances. + * Values may be `true` or `false`. + * @param {Boolean} [params.unfinished] Only include unfinished process instances. + * Values may be `true` or `false`. + * @param {String} [params.startedBy] Only include process instances that were started by the given user. + * @param {String} [params.startedBefore] Restrict to instances that were started before the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * @param {String} [params.startedAfter] Restrict to instances that were started after the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * @param {String} [params.finishedBefore] Restrict to instances that were finished before the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * @param {String} [params.finishedAfter] Restrict to instances that were finished after the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * @param {Object[]} [params.variables] A JSON array to only include process instances that have/had variables with certain values. The array consists of objects with the three properties name, operator and value. name (String) is the variable name, operator (String) is the comparison operator to be used and value the variable value. + * `value` may be String, Number or Boolean. + * Valid operator values are: + * - `eq` - equal to + * - `neq` - not equal to + * - `gt` - greater than + * - `gteq` - greater than or equal to + * - `lt` - lower than + * - `lteq` - lower than or equal to + * - `like` + * @param {String} [params.sortBy] Sort the results by a given criterion. + * Valid values are instanceId, definitionId, businessKey, startTime, endTime, duration. Must be used in conjunction with the sortOrder parameter. + * @param {String} [params.sortOrder] Sort the results in a given order. + * Values may be asc for ascending order or desc for descending order. Must be used in conjunction with the sortBy parameter. + * @param {Number} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {Number} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + + * @param {Function} done + */ +History.processInstance = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + var body = {}; + var query = {}; + var queryParams = ['firstResult', 'maxResults']; + + for (var p in params) { + if (queryParams.indexOf(p) > -1) { + query[p] = params[p]; + } else { + body[p] = params[p]; + } + } + + return this.http.post(this.path + '/process-instance', { + data: body, + query: query, + done: done + }); +}; + +/** + * Query for the number of historic process instances that fulfill the given parameters. + * This method takes the same message body as `History.processInstance`. + */ +History.processInstanceCount = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.post(this.path + '/process-instance/count', { + data: params, + done: done + }); +}; + +/** + * Delete finished process instances asynchronously. With creation of a batch operation. + * + * @param params - either list of process instance ID's or an object corresponding to a processInstances + * POST request based query + * @param done - a callback function + * @returns {*} + */ +History.deleteProcessInstancesAsync = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.post(this.path + '/process-instance/delete', { + data: params, + done: done + }); +}; + +/** + * Set removal time to historic process instances asynchronously. With creation of a batch operation. + * + * @param params - either list of process instance ID's or an object corresponding to a processInstances + * POST request based query + * @param done - a callback function + * @returns {*} + */ +History.setRemovalTimeToHistoricProcessInstancesAsync = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.post(this.path + '/process-instance/set-removal-time', { + data: params, + done: done + }); +}; + +/** + * Set removal time to historic decision instances asynchronously. With creation of a batch operation. + * + * @param params - either list of decision instance ID's or an object corresponding to a decisionInstances + * POST request based query + * @param done - a callback function + * @returns {*} + */ +History.setRemovalTimeToHistoricDecisionInstancesAsync = function( + params, + done +) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.post(this.path + '/decision-instance/set-removal-time', { + data: params, + done: done + }); +}; + +/** + * Set removal time to historic batches asynchronously. With creation of a batch operation. + * + * @param params - either list of batch ID's or an object corresponding to a batches + * POST request based query + * @param done - a callback function + * @returns {*} + */ +History.setRemovalTimeToHistoricBatchesAsync = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.post(this.path + '/batch/set-removal-time', { + data: params, + done: done + }); +}; + +/** + * Query for historic decision instances that fulfill the given parameters. + * + * @param {Object} [params] + * @param {uuid} [params.decisionInstanceId] Filter by decision instance id. + * @param {String} [params.decisionInstanceIdIn] Filter by decision instance ids. Must be a comma-separated list of decision instance ids. + * @param {uuid} [params.decisionDefinitionId] Filter by the decision definition the instances belongs to. + * @param {String} [params.decisionDefinitionKey] Filter by the key of the decision definition the instances belongs to. + * @param {String} [params.decisionDefinitionName] Filter by the name of the decision definition the instances belongs to. + * @param {uuid} [params.processDefinitionId] Filter by the process definition the instances belongs to. + * @param {String} [params.processDefinitionKey] Filter by the key of the process definition the instances belongs to. + * @param {uuid} [params.processInstanceId] Filter by the process instance the instances belongs to. + * @param {uuid} [params.activityIdIn] Filter by the activity ids the instances belongs to. Must be a comma-separated list of acitvity ids. + * @param {String} [params.activityInstanceIdIn] Filter by the activity instance ids the instances belongs to. Must be a comma-separated list of acitvity instance ids. + * @param {String} [params.evaluatedBefore] Restrict to instances that were evaluated before the given date. The date must have the format yyyy-MM-dd'T'HH:mm:ss, e.g., 2013-01-23T14:42:45. + * @param {String} [params.evaluatedAfter] Restrict to instances that were evaluated after the given date. The date must have the format yyyy-MM-dd'T'HH:mm:ss, e.g., 2013-01-23T14:42:45. + * @param {Boolean} [params.includeInputs] Include input values in the result. Value may only be true, as false is the default behavior. + * @param {Boolean} [params.includeOutputs] Include output values in the result. Value may only be true, as false is the default behavior. + * @param {Boolean} [params.disableBinaryFetching] Disables fetching of byte array input and output values. Value may only be true, as false is the default behavior. + * @param {Boolean} [params.disableCustomObjectDeserialization] Disables deserialization of input and output values that are custom objects. Value may only be true, as false is the default behavior. + * @param {String} [params.sortBy] Sort the results by a given criterion. + * Valid values are evaluationTime. Must be used in conjunction with the sortOrder parameter. + * @param {String} [params.sortOrder] Sort the results in a given order. + * Values may be asc for ascending order or desc for descending order. Must be used in conjunction with the sortBy parameter. + * @param {Number} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {Number} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + * @param {Function} done + */ +History.decisionInstance = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.get(this.path + '/decision-instance', { + data: params, + done: done + }); +}; + +/** + * Query for the number of historic decision instances that fulfill the given parameters. + * This method takes the same parameters as `History.decisionInstance`. + */ +History.decisionInstanceCount = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.get(this.path + '/decision-instance/count', { + data: params, + done: done + }); +}; + +/** + * Delete historic decision instances asynchronously. With creation of a batch operation. + * + * @param params - either list of decision instance ID's or an object corresponding to a decisionInstances + * POST request based query + * @param done - a callback function + * @returns {*} + */ +History.deleteDecisionInstancesAsync = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.post(this.path + '/decision-instance/delete', { + data: params, + done: done + }); +}; + +/** + * Query for historic batches that fulfill given parameters. Parameters may be the properties of batches, such as the id or type. + * The size of the result set can be retrieved by using the GET query count. + */ +History.batch = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.get(this.path + '/batch', { + data: params, + done: done + }); +}; + +/** + * Retrieves a single historic batch according to the HistoricBatch interface in the engine. + */ +History.singleBatch = function(id, done) { + return this.http.get(this.path + '/batch/' + id, { + done: done + }); +}; + +/** + * Request the number of historic batches that fulfill the query criteria. + * Takes the same filtering parameters as the GET query. + */ +History.batchCount = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.get(this.path + '/batch/count', { + data: params, + done: done + }); +}; + +History.batchDelete = function(id, done) { + var path = this.path + '/batch/' + id; + + return this.http.del(path, { + done: done + }); +}; + +/** + * Query for process instance durations report. + * @param {Object} [params] + * @param {Object} [params.reportType] Must be 'duration'. + * @param {Object} [params.periodUnit] Can be one of `month` or `quarter`, defaults to `month` + * @param {Object} [params.processDefinitionIn] Comma separated list of process definition IDs + * @param {Object} [params.startedAfter] Date after which the process instance were started + * @param {Object} [params.startedBefore] Date before which the process instance were started + * @param {Function} done + */ +History.report = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + params.reportType = params.reportType || 'duration'; + params.periodUnit = params.periodUnit || 'month'; + + return this.http.get(this.path + '/process-instance/report', { + data: params, + done: done + }); +}; + +/** + * Query for process instance durations report. + * @param {Object} [params] + * @param {Object} [params.reportType] Must be 'duration'. + * @param {Object} [params.periodUnit] Can be one of `month` or `quarter`, defaults to `month` + * @param {Object} [params.processDefinitionIn] Comma separated list of process definition IDs + * @param {Object} [params.startedAfter] Date after which the process instance were started + * @param {Object} [params.startedBefore] Date before which the process instance were started + * @param {Function} done + */ +History.reportAsCsv = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + params.reportType = params.reportType || 'duration'; + params.periodUnit = params.periodUnit || 'month'; + + return this.http.get(this.path + '/process-instance/report', { + data: params, + accept: 'text/csv', + done: done + }); +}; + +/** + * Query for historic task instances that fulfill the given parameters. + * + * @param {Object} [params] + * @param {uuid} [params.taskId] Filter by taskId. + * @param {uuid} [params.taskParentTaskId] Filter by parent task id. + * @param {uuid} [params.processInstanceId] Filter by process instance id. + * @param {uuid} [params.executionId] Filter by the id of the execution that executed the task. + * @param {uuid} [params.processDefinitionId] Filter by process definition id. + * @param {String} [params.processDefinitionKey] Restrict to tasks that belong to a process definition with the given key. + * @param {String} [params.processDefinitionName] Restrict to tasks that belong to a process definition with the given name. + * @param {uuid} [params.caseInstanceId] Filter by case instance id. + + * @param {uuid} [params.caseExecutionId] Filter by the id of the case execution that executed the task. + * @param {uuid} [params.caseDefinitionId] Filter by case definition id. + * @param {String} [params.caseDefinitionKey] Restrict to tasks that belong to a case definition with the given key. + * @param {String} [params.caseDefinitionName] Restrict to tasks that belong to a case definition with the given name. + * @param {uuid[]} [params.activityInstanceIdIn] Only include tasks which belong to one of the passed activity instance ids. + * Must be a json array of activity instance ids. + * @param {String} [params.taskName] Restrict to tasks that have the given name. + * @param {String} [params.taskNameLike] Restrict to tasks that have a name with the given parameter value as substring. + * @param {String} [params.taskDescription] Restrict to tasks that have the given description. + * @param {String} [params.taskDescriptionLike] Restrict to tasks that have a description that has the parameter value as a substring. + * @param {String} [params.taskDefinitionKey] Restrict to tasks that have the given key. + * @param {String} [params.taskDeleteReason] Restrict to tasks that have the given delete reason. + * @param {String} [params.taskDeleteReasonLike] Restrict to tasks that have a delete reason that has the parameter value as a substring. + * @param {String} [params.taskAssignee] Restrict to tasks that the given user is assigned to. + * @param {String} [params.taskAssigneeLike] Restrict to tasks that are assigned to users with the parameter value as a substring. + * @param {String} [params.taskOwner] Restrict to tasks that the given user owns. + * @param {String} [params.taskOwnerLike] Restrict to tasks that are owned by users with the parameter value as a substring. + * @param {String} [params.taskPriority] Restrict to tasks that have the given priority. + * @param {String} [params.assigned] If set to true, restricts the query to all tasks that are assigned. + * Values may be `true` or `false`. + * @param {String} [params.unassigned] If set to true, restricts the query to all tasks that are unassigned. + * Values may be `true` or `false`. + * @param {String} [params.finished] Only include finished tasks. Value may only be true, as false is the default behavior. + * @param {String} [params.unfinished] Only include unfinished tasks. Value may only be true, as false is the default behavior. + * @param {String} [params.processFinished] Only include tasks of finished processes. Value may only be true, as false is the default behavior. + * @param {String} [params.processUnfinished] Only include tasks of unfinished processes. Value may only be true, as false is the default behavior. + * @param {Date} [params.taskDueDate] Restrict to tasks that are due on the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * @param {Date} [params.taskDueDateBefore] RestRestrict to tasks that are due before the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * @param {Date} [params.taskDueDateAfter] Restrict to tasks that are due after the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * @param {Date} [params.taskFollowUpDate] ReRestrict to tasks that have a followUp date on the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * @param {Date} [params.taskFollowUpDateBefore] Restrict to tasks that have a followUp date before the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * @param {Date} [params.taskFollowUpDateAfter] Restrict to tasks that have a followUp date after the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * @param {uuid[]} [params.tenantIdIn] Filter by a comma-separated list of tenant ids. A task instance must have one of the given tenant ids. + * Must be a json array of tenant ids. + * @param {Object[]} [params.taskVariables] A JSON array to only include process instances that have/had variables with certain values. The array consists of objects with the three properties name, operator and value. name (String) is the variable name, operator (String) is the comparison operator to be used and value the variable value. + * `value` may be String, Number or Boolean. + * Valid operator values are: + * - `eq` - equal to + * - `neq` - not equal to + * - `gt` - greater than + * - `gteq` - greater than or equal to + * - `lt` - lower than + * - `lteq` - lower than or equal to + * - `like` + * @param {Object[]} [params.processVariables] A JSON array to only include process instances that have/had variables with certain values. The array consists of objects with the three properties name, operator and value. name (String) is the variable name, operator (String) is the comparison operator to be used and value the variable value. + * `value` may be String, Number or Boolean. + * Valid operator values are: + * - `eq` - equal to + * - `neq` - not equal to + * - `gt` - greater than + * - `gteq` - greater than or equal to + * - `lt` - lower than + * - `lteq` - lower than or equal to + * - `like` + * @param {String} [params.taskInvolvedUser] Restrict on the historic identity links of any type of user. + * @param {String} [params.taskInvolvedGroup] Restrict on the historic identity links of any type of group. + * @param {String} [params.taskHadCandidateUser] Restrict on the historic identity links of type candidate user. + * @param {String} [params.taskHadCandidateGroup] Restrict on the historic identity links of type candidate group. + * @param {String} [params.withCandidateGroups] Only include tasks which have a candidate group. Value may only be true, as false is the default behavior. + * @param {String} [params.withoutCandidateGroups] Only include tasks which have no candidate group. Value may only be true, as false is the default behavior. + * @param {String} [params.sortBy] Sort the results by a given criterion. + * Valid values are taskId, activityInstanceID, processDefinitionId, processInstanceId, executionId, + * duration, endTime, startTime, taskName, taskDescription, assignee, owner, dueDate, followUpDate, + * deleteReason, taskDefinitionKey, priority, caseDefinitionId, caseInstanceId, caseExecutionId and + * tenantId. Must be used in conjunction with the sortOrder parameter. + * @param {String} [params.sortOrder] Sort the results in a given order. + * Values may be asc for ascending order or desc for descending order. Must be used in conjunction with the sortBy parameter. + * @param {Number} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {Number} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + + * @param {Function} done + */ +History.task = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + var body = {}; + var query = {}; + var queryParams = ['firstResult', 'maxResults']; + + for (var p in params) { + if (queryParams.indexOf(p) > -1) { + query[p] = params[p]; + } else { + body[p] = params[p]; + } + } + + return this.http.post(this.path + '/task', { + data: body, + query: query, + done: done + }); +}; + +/** + * Query for the number of historic task instances that fulfill the given parameters. + * This method takes the same parameters as `History.task`. + */ +History.taskCount = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.post(this.path + '/task/count', { + data: params, + done: done + }); +}; + +/** + * Query for a historic task instance duration report. + * + * @param {Object} [params] + * @param {Date} [params.completedBefore] Restrict to tasks which are completed before a given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, + * e.g., 2013-01-23T14:42:45. + * @param {Date} [params.completedAfter] Restrict to tasks which are completed after a given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, + * e.g., 2013-01-23T14:42:45. + * @param {String} [params.periodUnit] Can be one of `month` or `quarter`, defaults to `month` + * @param {Function} done + */ +History.taskDurationReport = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + params.reportType = params.reportType || 'duration'; + params.periodUnit = params.periodUnit || 'month'; + + return this.http.get(this.path + '/task/report', { + data: params, + done: done + }); +}; + +/** + * Query for a completed task instance report + * + * @param {Object} [params] + * @param {Date} [params.completedBefore] Restrict to tasks which are completed before a given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, + * e.g., 2013-01-23T14:42:45. + * @param {Date} [params.completedAfter] Restrict to tasks which are completed after a given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, + * e.g., 2013-01-23T14:42:45. + * @param {String} [params.groupBy] Groups the task report by `taskDefinitionKey` (Default) or + * `processDefinitionKey`. Valid values are `taskDefinition` or + * `processDefinition`. + * @param done + * @returns {*} + */ +History.taskReport = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + params.reportType = params.reportType || 'count'; + + return this.http.get(this.path + '/task/report', { + data: params, + done: done + }); +}; + +/** + * Query for historic case instances that fulfill the given parameters. + * + * @param {Object} [params] + * @param {uuid} [params.caseInstanceId] Filter by case instance id. + * @param {uuid[]} [params.caseInstanceIds] Filter by case instance ids. + * Must be a json array case instance ids. + * + * @param {uuid} [params.caseDefinitionId] Filter by the case definition the instances run on. + * @param {String} [params.caseDefinitionKey] Filter by the key of the case definition the instances run on. + * @param {String[]} [params.caseDefinitionKeyNotIn] Exclude instances that belong to a set of case definitions. + * + * @param {String} [params.caseDefinitionName] Filter by the name of the case definition the instances run on. + * @param {String} [params.caseDefinitionNameLike] Filter by case definition names that the parameter is a substring of. + * + * @param {String} [params.caseInstanceBusinessKey] Filter by case instance business key. + * @param {String} [params.caseInstanceBusinessKeyLike] Filter by case instance business key that the parameter is a substring of. + * + * + * @param {String} [params.createdBefore] Restrict to instances that were created before the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * @param {String} [params.createdAfter] Restrict to instances that were created after the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * + * @param {String} [params.closedBefore] Restrict to instances that were closed before the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * @param {String} [params.closedAfter] Restrict to instances that were closed after the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * + * @param {String} [params.createdBy] Only include case instances that were created by the given user. + * + * + * @param {uuid} [params.superCaseInstanceId] Restrict query to all case instances that are sub case instances of the given case instance. + * Takes a case instance id. + * @param {uuid} [params.subCaseInstanceId] Restrict query to one case instance that has a sub case instance with the given id. + * + * @param {uuid} [params.superProcessInstanceId] Restrict query to all process instances that are sub case instances of the given process instance. + * Takes a process instance id. + * @param {uuid} [params.subProcessInstanceId] Restrict query to one case instance that has a sub process instance with the given id. + * + * @param {uuid} [params.tenantIdIn] Filter by a comma-separated list of tenant ids. A case instance must have one of the given tenant ids. + * + * @param {Boolean} [params.active] Only include active case instances. + * Values may be `true` or `false`. + * @param {Boolean} [params.completed] Only include completed case instances. + * Values may be `true` or `false`. + * @param {Boolean} [params.terminated] Only include terminated case instances. + * Values may be `true` or `false`. + * @param {Boolean} [params.closed] Only include closed case instances. + * Values may be `true` or `false`. + * @param {Boolean} [params.notClosed] Only include not closed case instances. + * Values may be `true` or `false`. + * + * @param {Object[]} [params.variables] A JSON array to only include case instances that have/had variables with certain values. The array consists of objects with the three properties name, operator and value. name (String) is the variable name, operator (String) is the comparison operator to be used and value the variable value. + * `value` may be String, Number or Boolean. + * Valid operator values are: + * - `eq` - equal to + * - `neq` - not equal to + * - `gt` - greater than + * - `gteq` - greater than or equal to + * - `lt` - lower than + * - `lteq` - lower than or equal to + * - `like` + * + * @param {String} [params.sortBy] Sort the results by a given criterion. + * Valid values are instanceId, definitionId, businessKey, startTime, endTime, duration. Must be used in conjunction with the sortOrder parameter. + * @param {String} [params.sortOrder] Sort the results in a given order. + * Values may be asc for ascending order or desc for descending order. Must be used in conjunction with the sortBy parameter. + * @param {Number} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {Number} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + + * @param {Function} done + */ +History.caseInstance = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + var body = {}; + var query = {}; + var queryParams = ['firstResult', 'maxResults']; + + for (var p in params) { + if (queryParams.indexOf(p) > -1) { + query[p] = params[p]; + } else { + body[p] = params[p]; + } + } + + return this.http.post(this.path + '/case-instance', { + data: body, + query: query, + done: done + }); +}; + +/** + * Query for the number of historic case instances that fulfill the given parameters. + * This method takes the same parameters as `History.caseInstance`. + */ +History.caseInstanceCount = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.post(this.path + '/case-instance/count', { + data: params, + done: done + }); +}; + +/** + * Query for historic case activty instances that fulfill the given parameters. + * + * @param {Object} [params] + * @param {uuid} [params.caseActivityInstanceId] Filter by case activity instance id. + * @param {String} [params.caseExecutionId] Filter by the id of the case execution that executed the case activity instance. + * @param {uuid} [params.caseInstanceId] Filter by case instance id. + * + * @param {uuid} [params.caseDefinitionId] Filter by the case definition the instances run on. + * + * @param {String} [params.caseActivityId] Filter by the case activity id. + * @param {String} [params.caseActivityName] Filter by the case activity name. + * @param {String} [params.caseActivityType] Filter by the case activity type. + * + * @param {String} [params.createdBefore] Restrict to instances that were created before the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * @param {String} [params.createdAfter] Restrict to instances that were created after the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * + * @param {String} [params.endedBefore] Restrict to instances that were ended before the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * @param {String} [params.endedAfter] Restrict to instances that were ended after the given date. + * The date must have the format `yyyy-MM-dd'T'HH:mm:ss`, e.g., 2013-01-23T14:42:45. + * + * @param {Boolean} [params.required] Only include required case activity instances. + * Values may be `true` or `false`. + * + * @param {Boolean} [params.finished] Only include finished case activity instances. + * Values may be `true` or `false`. + * @param {Boolean} [params.unfinished] Only include unfinished case activity instances. + * Values may be `true` or `false`. + * @param {Boolean} [params.available] Only include available case activity instances. + * Values may be `true` or `false`. + * @param {Boolean} [params.enabled] Only include enabled case activity instances. + * Values may be `true` or `false`. + * @param {Boolean} [params.disabled] Only include disabled case activity instances. + * Values may be `true` or `false`. + * @param {Boolean} [params.active] Only include active case activity instances. + * Values may be `true` or `false`. + * + * @param {Boolean} [params.completed] Only include completed case activity instances. + * Values may be `true` or `false`. + * + * @param {Boolean} [params.terminated] Only include terminated case activity instances. + * Values may be `true` or `false`. + * + * @param {uuid[]} [params.tenantIdIn] Filter by a comma-separated list of tenant ids. A case activity instance must have one of the given tenant ids. + * + * @param {String} [params.sortBy] Sort the results by a given criterion. + * Valid values are caseActivityInstanceId, caseInstanceId, caseExecutionId, caseActivityId, caseActivityName, createTime, endTime, duration, + * caseDefinitionId and tenantId. Must be used in conjunction with the sortOrder parameter. + * @param {String} [params.sortOrder] Sort the results in a given order. + * Values may be asc for ascending order or desc for descending order. Must be used in conjunction with the sortBy parameter. + * @param {Number} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {Number} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + + * @param {Function} done + */ +History.caseActivityInstance = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.get(this.path + '/case-activity-instance', { + data: params, + done: done + }); +}; + +/** + * Query for the number of historic case activity instances that fulfill the given parameters. + * This method takes the same parameters as `History.caseActivityInstance`. + */ +History.caseActivityInstanceCount = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.get(this.path + '/case-activity-instance/count', { + data: params, + done: done + }); +}; + +/** + * Queries for historic activity instances that fulfill the given parameters. + * @param {Object} [params] + * @param {String} params.activityInstanceId Filter by activity instance id. + * @param {String} params.processInstanceId Filter by process instance id. + * @param {String} params.processDefinitionId Filter by process definition id. + * @param {String} params.executionId Filter by the id of the execution that executed the activity instance. + * @param {String} params.activityId Filter by the activity id (according to BPMN 2.0 XML). + * @param {String} params.activityName Filter by the activity name (according to BPMN 2.0 XML). + * @param {String} params.activityType Filter by activity type. + * @param {String} params.taskAssignee Only include activity instances that are user tasks and assigned to a given user. + * @param {Boolean} params.finished Only include finished activity instances. Value may only be true, as false behaves the same as when the property is not set. + * @param {Boolean} params.unfinished Only include unfinished activity instances. Value may only be true, as false behaves the same as when the property is not set. + * @param {Boolean} params.canceled Only include canceled activity instances. Value may only be true, as false behaves the same as when the property is not set. + * @param {Boolean} params.completeScope Only include activity instances which completed a scope. Value may only be true, as false behaves the same as when the property is not set. + * @param {String} params.startedBefore Restrict to instances that were started before the given date. By default*, the date must have the format yyyy-MM-dd'T'HH:mm:ss.SSSZ, e.g., 2013-01-23T14:42:45.000+0200. + * @param {String} params.startedAfter Restrict to instances that were started after the given date. By default*, the date must have the format yyyy-MM-dd'T'HH:mm:ss.SSSZ, e.g., 2013-01-23T14:42:45.000+0200. + * @param {String} params.finishedBefore Restrict to instances that were finished before the given date. By default*, the date must have the format yyyy-MM-dd'T'HH:mm:ss.SSSZ, e.g., 2013-01-23T14:42:45.000+0200. + * @param {String} params.finishedAfter Restrict to instances that were finished after the given date. By default*, the date must have the format yyyy-MM-dd'T'HH:mm:ss.SSSZ, e.g., 2013-01-23T14:42:45.000+0200. + * @param {String} params.tenantIdIn Filter by a comma-separated list of tenant ids. An activity instance must have one of the given tenant ids. + * @param {String} params.sortBy Sort the results by a given criterion. Valid values are activityInstanceId, instanceId, executionId, activityId, activityName, activityType, startTime, endTime, duration, definitionId, occurrence and tenantId. Must be used in conjunction with the sortOrder parameter. + * @param {String} params.sortOrder Sort the results in a given order. Values may be asc for ascending order or desc for descending order. Must be used in conjunction with the sortBy parameter. + * @param {Number} params.firstResult Pagination of results. Specifies the index of the first result to return. + * @param {Number} params.maxResults Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + */ +History.activityInstance = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.get(this.path + '/activity-instance', { + data: params, + done: done + }); +}; + +/** + * Queries for historic activity instances that fulfill the given parameters. + * @param {Object} [params] + * @param {String} params.incidentId Restricts to incidents that have the given id. + * @param {String} params.incidentType Restricts to incidents that belong to the given incident type. See the User Guide for a list of incident types. + * @param {String} params.incidentMessage Restricts to incidents that have the given incident message. + * @param {String} params.processDefinitionId Restricts to incidents that belong to a process definition with the given id. + * @param {String} params.processInstanceId Restricts to incidents that belong to a process instance with the given id. + * @param {String} params.executionId Restricts to incidents that belong to an execution with the given id. + * @param {String} params.activityId Restricts to incidents that belong to an activity with the given id. + * @param {String} params.causeIncidentId Restricts to incidents that have the given incident id as cause incident. + * @param {String} params.rootCauseIncidentId Restricts to incidents that have the given incident id as root cause incident. + * @param {String} params.configuration Restricts to incidents that have the given parameter set as configuration. + * @param {String} params.tenantIdIn Restricts to incidents that have one of the given comma-separated tenant ids. + * @param {String} params.jobDefinitionIdIn Restricts to incidents that have one of the given comma-separated job definition ids. + * @param {String} params.open Restricts to incidents that are open. + * @param {String} params.deleted Restricts to incidents that are deleted. + * @param {String} params.resolved Restricts to incidents that are resolved. + * @param {String} params.sortBy Sort the results lexicographically by a given criterion. Valid values are incidentId, incidentMessage, createTime, endTime, incidentType, executionId, activityId, processInstanceId, processDefinitionId, causeIncidentId, rootCauseIncidentId, configuration, tenantId and incidentState. Must be used in conjunction with the sortOrder parameter. + * @param {String} params.sortOrder Sort the results in a given order. Values may be asc for ascending order or desc for descending order. Must be used in conjunction with the sortBy parameter. + */ +History.incident = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.get(this.path + '/incident', { + data: params, + done: done + }); +}; + +/** + * Query for historic variable instances that fulfill the given parameters. + * + * @param {Object} [params] + * @param {uuid} [params.variableName] Filter by variable name. + * @param {String} [params.variableNameLike] Restrict to variables with a name like the parameter. + * @param {uuid[]} [params.variableValue] Filter by variable value. + * + * @param {uuid} [params.processInstanceId] Filter by the process instance the variable belongs to. + * @param {String[]} [params.executionIdIn] Filter by the execution ids. + * @param {String} [params.caseInstanceId] Filter by the case instance id. + * @param {String[]} [params.caseExecutionIdIn] Filter by the case execution ids. + * @param {String[]} [params.taskIdIn] Filter by the task ids. + * @param {String[]} [params.activityInstanceIdIn] Filter by the activity instance ids. + * + * @param {uuid[]} [params.tenantIdIn] Filter by a comma-separated list of tenant ids. A case activity instance must have one of the given tenant ids. + * + * @param {String} [params.sortBy] Sort the results by a given criterion. + * Valid values are instanceId, variableName and tenantId. Must be used in conjunction with the sortOrder parameter. + * @param {String} [params.sortOrder] Sort the results in a given order. + * Values may be asc for ascending order or desc for descending order. Must be used in conjunction with the sortBy parameter. + * @param {Number} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {Number} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + + * @param {Function} done + */ +History.variableInstance = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + var body = {}; + var query = {}; + var queryParams = ['firstResult', 'maxResults', 'deserializeValues']; + + for (var p in params) { + if (queryParams.indexOf(p) > -1) { + query[p] = params[p]; + } else { + body[p] = params[p]; + } + } + + return this.http.post(this.path + '/variable-instance', { + data: body, + query: query, + done: done + }); +}; + +/** + * Query for the number of historic variable instances that fulfill the given parameters. + * This method takes the same parameters as `History.variableInstance`. + */ +History.variableInstanceCount = function(params, done) { + if (typeof params === 'function') { + done = arguments[0]; + params = {}; + } + + return this.http.post(this.path + '/variable-instance/count', { + data: params, + done: done + }); +}; + +History.caseActivityStatistics = function(params, done) { + var id = params.id || params; + + return this.http.get(this.path + '/case-definition/' + id + '/statistics', { + done: done + }); +}; + +History.drdStatistics = function(id, params, done) { + var url = + this.path + '/decision-requirements-definition/' + id + '/statistics'; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(url, { + data: params, + done: done + }); +}; + +/** + * Query for the history cleanup configuration + */ +History.cleanupConfiguration = function(params, done) { + var url = this.path + '/cleanup/configuration'; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(url, { + data: params, + done: done + }); +}; + +/** + * Delete the history of a single variable + */ + +History.deleteVariable = function(id, done) { + var url = this.path + '/variable-instance/' + id; + + return this.http.del(url, { + done: done + }); +}; + +/** + * Delete the history of a single variable + */ + +History.deleteAllVariables = function(id, done) { + var url = this.path + '/process-instance/' + id + '/variable-instances'; + + return this.http.del(url, { + done: done + }); +}; + +/** + * Query for the history cleanup job + */ +History.cleanupJobs = function(params, done) { + var url = this.path + '/cleanup/jobs'; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(url, { + data: params, + done: done + }); +}; + +/** + * Query to start a history cleanup job + * @param {Object} [params] + * @param {Boolean} [params.executeAtOnce] Execute job in nearest future + */ +History.cleanup = function(params, done) { + var url = this.path + '/cleanup'; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.post(url, { + data: params, + done: done + }); +}; + +/** + * Query for the count of the finished historic process instances, cleanable process instances and basic process definition data - id, key, name and version + * @param {Object} [params] + * @param {uuid[]} [params.processDefinitionIdIn] Array of processDefinition ids + * @param {uuid[]} [params.processDefinitionKeyIn] Array of processDefinition keys + * @param {Number} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {Number} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + */ +History.cleanableProcessCount = function(params, done) { + var url = + this.path + '/process-definition/cleanable-process-instance-report/count'; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(url, { + data: params, + done: done + }); +}; + +/** + * Query for the report results about a process definition and finished process instances relevant to history cleanup + * This method takes the same parameterers as 'History.cleanableProcessInstanceCount' + */ +History.cleanableProcess = function(params, done) { + var url = this.path + '/process-definition/cleanable-process-instance-report'; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(url, { + data: params, + done: done + }); +}; + +/** + * Query for the count of the finished historic case instances, cleanable case instances and basic case definition data - id, key, name and version. + * @param {uuid[]} [params.caseDefinitionIdIn] Array of caseDefinition ids + * @param {uuid[]} [params.caseDefinitionKeyIn] Array of caseDefinition keys + * @param {Number} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {Number} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + */ +History.cleanableCaseCount = function(params, done) { + var url = this.path + '/case-definition/cleanable-case-instance-report/count'; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(url, { + data: params, + done: done + }); +}; + +/** + * Query for the report results about a case definition and finished case instances relevant to history cleanup + * This method takes the same parameterers as 'History.cleanableCaseInstanceCount ' + */ +History.cleanableCase = function(params, done) { + var url = this.path + '/case-definition/cleanable-case-instance-report'; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(url, { + data: params, + done: done + }); +}; + +/** + * Query for the count of the finished historic decision instances, cleanable decision instances and basic decision definition data - id, key, name and version + * @param {Object} [params] + * @param {uuid[]} [params.decisionDefinitionIdIn] Array of decisionDefinition ids + * @param {uuid[]} [params.decisionDefinitionKeyIn] Array of decisionDefinition keys + * @param {Number} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {Number} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + */ +History.cleanableDecisionCount = function(params, done) { + var url = + this.path + '/decision-definition/cleanable-decision-instance-report/count'; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(url, { + data: params, + done: done + }); +}; + +/** + * Query for the report results about a decision definition and finished decision instances relevant to history cleanup + * This method takes the same parameterers as 'History.cleanableDecisionInstanceCount ' + */ +History.cleanableDecision = function(params, done) { + var url = + this.path + '/decision-definition/cleanable-decision-instance-report'; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(url, { + data: params, + done: done + }); +}; + +/** + * Query for the count of report results about historic batch operations relevant to history cleanup + * @param {Object} [params] + * @param {Number} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {Number} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + */ +History.cleanableBatchCount = function(params, done) { + var url = this.path + '/batch/cleanable-batch-report/count'; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(url, { + data: params, + done: done + }); +}; + +/** + * Query for the report about historic batch operations relevant to history cleanup + * This method takes the same parameterers as 'History.cleanableBatchCount' + */ +History.cleanableBatch = function(params, done) { + var url = this.path + '/batch/cleanable-batch-report'; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(url, { + data: params, + done: done + }); +}; + +History.jobLogList = function(params, done) { + var url = this.path + '/job-log'; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(url, { + data: params, + done: done + }); +}; + +History.jobLogCount = function(params, done) { + var url = this.path + '/job-log/count'; + + if (typeof params === 'function') { + done = params; + params = {}; + } + + return this.http.get(url, { + data: params, + done: done + }); +}; + +History.externalTaskLogList = helpers.createSimpleGetQueryFunction( + '/external-task-log' +); +History.externalTaskLogCount = helpers.createSimpleGetQueryFunction( + '/external-task-log/count' +); + +module.exports = History; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/incident.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/incident.js new file mode 100644 index 0000000000000000000000000000000000000000..ecd5d9184c0699fec616afaa8707da3fb107a543 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/incident.js @@ -0,0 +1,149 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * Incident Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Incident = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +Incident.path = 'incident'; + +/** + * Query for incidents that fulfill given parameters. The size of the result set can be retrieved by using the get incidents count method. + * + * @param {Object} params + * + * @param {String} [params.incidentId] Restricts to incidents that have the given id. + * + * @param {String} [params.incidentType] Restricts to incidents that belong to the given incident type. + * + * @param {String} [params.incidentMessage] Restricts to incidents that have the given incident message. + * + * @param {String} [params.processDefinitionId] Restricts to incidents that belong to a process definition with the given id. + * + * @param {String} [params.processInstanceId] Restricts to incidents that belong to a process instance with the given id. + * + * @param {String} [params.executionId] Restricts to incidents that belong to an execution with the given id. + * + * @param {String} [params.activityId] Restricts to incidents that belong to an activity with the given id. + * + * @param {String} [params.causeIncidentId] Restricts to incidents that have the given incident id as cause incident. + * + * @param {String} [params.rootCauseIncidentId] Restricts to incidents that have the given incident id as root cause incident. + * + * @param {String} [params.configuration] Restricts to incidents that have the given parameter set as configuration. + * + * @param {String} [params.sortBy] Sort the results lexicographically by a given criterion. Valid values are + * incidentId, incidentTimestamp, incidentType, executionId, activityId, + * processInstanceId, processDefinitionId, causeIncidentId, rootCauseIncidentId + * and configuration. Must be used in conjunction with the sortOrder parameter. + * + * @param {String} [params.sortOrder] Sort the results in a given order. Values may be asc for ascending order or + * desc for descending order. Must be used in conjunction with the sortBy parameter. + * + * @param {String} [params.firstResult] Pagination of results. Specifies the + * index of the first result to return. + * + * @param {String} [params.maxResults] Pagination of results. Specifies the + * maximum number of results to return. + * Will return less results if there are no + * more results left. + * + * @param {RequestCallback} done + */ +Incident.get = function(params, done) { + return this.http.get(this.path, { + data: params, + done: done + }); +}; + +/** + * Query for the number of incidents that fulfill given parameters. Takes the same parameters as the get incidents method. + * + * @param {Object} params + * + * @param {String} [params.incidentId] Restricts to incidents that have the given id. + * + * @param {String} [params.incidentType] Restricts to incidents that belong to the given incident type. + * + * @param {String} [params.incidentMessage] Restricts to incidents that have the given incident message. + * + * @param {String} [params.processDefinitionId] Restricts to incidents that belong to a process definition with the given id. + * + * @param {String} [params.processInstanceId] Restricts to incidents that belong to a process instance with the given id. + * + * @param {String} [params.executionId] Restricts to incidents that belong to an execution with the given id. + * + * @param {String} [params.activityId] Restricts to incidents that belong to an activity with the given id. + * + * @param {String} [params.causeIncidentId] Restricts to incidents that have the given incident id as cause incident. + * + * @param {String} [params.rootCauseIncidentId] Restricts to incidents that have the given incident id as root cause incident. + * + * @param {String} [params.configuration] Restricts to incidents that have the given parameter set as configuration. + * + * @param {RequestCallback} done + */ +Incident.count = function(params, done) { + return this.http.get(this.path + '/count', { + data: params, + done: done + }); +}; + +/** + * Set the annotation of an incident with the given id. + * + * @param {Object} [params] + * @param {String} [params.id] Incident ID to set the Annotation + * @param {String} [params.annotation] An arbitrary text annotation set by a user. + * @param {Function} done + */ + +Incident.setAnnotation = function(params, done) { + return this.http.put(this.path + '/' + params.id + '/annotation', { + data: params, + done: done + }); +}; + +/** + * Clear the annotation of an incident with the given id. + * + * @param {String} [id] The Incident id to be updated. + * @param {Function} done + */ + +Incident.clearAnnotation = function(id, done) { + return this.http.delete(this.path + '/' + id + '/annotation', { + done: done + }); +}; + +module.exports = Incident; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/job-definition.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/job-definition.js new file mode 100644 index 0000000000000000000000000000000000000000..31005c796bdaf4ac80b95fdb55a2cf90737c748b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/job-definition.js @@ -0,0 +1,46 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +var JobDefinition = AbstractClientResource.extend(); + +JobDefinition.path = 'job-definition'; + +JobDefinition.setRetries = function(params, done) { + return this.http.put(this.path + '/' + params.id + '/retries', { + data: params, + done: done + }); +}; + +JobDefinition.list = function(params, done) { + return this.http.get(this.path, { + data: params, + done: done + }); +}; + +JobDefinition.get = function(id, done) { + return this.http.get(this.path + '/' + id, { + done: done + }); +}; + +module.exports = JobDefinition; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/job.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/job.js new file mode 100644 index 0000000000000000000000000000000000000000..051500e349c1fa72832bd69f0d2a408b986a1486 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/job.js @@ -0,0 +1,159 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * Job Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Job = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +Job.path = 'job'; + +Job.get = function(id, done) { + return this.http.get(this.path + '/' + id, { + done: done + }); +}; + +/** + * Query for jobs that fulfill given parameters. + * @param {Object} params + * @param {String} [params.jobId] Filter by job id. + * @param {String} [params.processInstanceId] Only select jobs which exist for the given process instance. + * @param {String} [params.executionId] Only select jobs which exist for the given execution. + * @param {String} [params.processDefinitionId] Filter by the id of the process definition the jobs run on. + * @param {String} [params.processDefinitionKey] Filter by the key of the process definition the jobs run on. + * @param {String} [params.activityId] Only select jobs which exist for an activity with the given id. + * @param {Bool} [params.withRetriesLeft] Only select jobs which have retries left. + * @param {Bool} [params.executable] Only select jobs which are executable, ie. retries > 0 and due date is null or due date is in the past. + * @param {Bool} [params.timers] Only select jobs that are timers. Cannot be used together with messages. + * @param {Bool} [params.messages] Only select jobs that are messages. Cannot be used together with timers. + * @param {String} [params.dueDates] Only select jobs where the due date is lower or higher than the given date. Due date expressions are comma-separated and are structured as follows: + * A valid condition value has the form operator_value. operator is the comparison operator to be used and value the date value as string. + * Valid operator values are: gt - greater than; lt - lower than. + * value may not contain underscore or comma characters. + * @param {Bool} [params.withException] Only select jobs that failed due to an exception. + * @param {String} [params.exceptionMessage] Only select jobs that failed due to an exception with the given message. + * @param {Bool} [params.noRetriesLeft] Only select jobs which have no retries left. + * @param {Bool} [params.active] Only include active jobs. + * @param {Bool} [params.suspended] Only include suspended jobs. + * @param {Array} [params.sorting] A JSON array of criteria to sort the result by. Each element of the array is a JSON object that specifies one ordering. The position in the array identifies the rank of an ordering, i.e. whether it is primary, secondary, etc. + * @param {String} params.sorting.sortBy Sort the results lexicographically by a given criterion. Valid values are jobId, executionId, processInstanceId, jobRetries and jobDueDate. + * @param {String} params.sorting.sortOrder Sort the results in a given order. Values may be asc for ascending order or desc for descending order. + * @param {String} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {String} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + * @param {Bool} [params.acquired] Select jobs which are acquired, ie. lock expiration time is not + * null,lock expiration is in future + * @param {Function} done + */ +Job.list = function(params, done) { + var path = this.path; + + // those parameters have to be passed in the query and not body + path += '?firstResult=' + (params.firstResult || 0); + if (params.maxResults) { + path += '&maxResults=' + params.maxResults; + } + + return this.http.post(path, { + data: params, + done: done + }); +}; + +/** + * Sets the retries of the job to the given number of retries. + * @param {Object} params + * @param {String} params.id The id of the job. + * @param {String} params.retries The number of retries to set that a job has left. + * @param {Function} done + */ +Job.setRetries = function(params, done) { + return this.http.put(this.path + '/' + params.id + '/retries', { + data: params, + done: done + }); +}; + +Job.delete = function(id, done) { + return this.http.del(this.path + '/' + id, { + done: done + }); +}; + +Job.stacktrace = function(id, done) { + var url = this.path + '/' + id + '/stacktrace'; + return this.http.get(url, { + accept: 'text/plain', + done: done + }); +}; + +/** + * Recalculates the duedate for a given job. + * @param {Object} params + * @param {String} params.id The id of the job.Job + * @param {Bool} params.creationDateBased Base recalculation on Job creation date. Default: true + * @param {Function} done + */ +Job.recalculateDuedate = function(params, done) { + var url = this.path + '/' + params.id + '/duedate/recalculate'; + + if (params.creationDateBased == false) { + url += '?creationDateBased=' + params.creationDateBased; + } + return this.http.post(url, { + done: done + }); +}; + +/** + * Sets the duedate of the job to the given date. + * @param {Object} params + * @param {String} params.id The id of the job. + * @param {String} params.duedate The duedate of the job. + * @param {Function} done + */ + +Job.setDuedate = function(params, done) { + var url = this.path + '/' + params.id + '/duedate'; + return this.http.put(url, { + data: params, + done: done + }); +}; + +Job.suspended = function(params, done) { + return this.http.put(this.path + '/' + params.id + '/suspended', { + data: { + suspended: !!params.suspended + }, + done: done + }); +}; + +module.exports = Job; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/message.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/message.js new file mode 100644 index 0000000000000000000000000000000000000000..4c028078362443c5e6b96a921ba9ab888020ed0e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/message.js @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * Message Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Message = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +Message.path = 'message'; + +/** + * correlates a message + * + * @param {Object} [params] + * @param {String} [params.messageName] The message name of the message to be corrolated + * @param {String} [params.businessKey] The business key the workflow instance is to be initialized with. The business key identifies the workflow instance in the context of the given workflow definition. + * @param {String} [params.correlationKeys] A JSON object containing the keys the recieve task is to be corrolated with. Each key corresponds to a variable name and each value to a variable value. + * @param {String} [params.processVariables] A JSON object containing the variables the recieve task is to be corrolated with. Each key corresponds to a variable name and each value to a variable value. + */ +Message.correlate = function(params, done) { + var url = this.path + '/'; + + return this.http.post(url, { + data: params, + done: done + }); +}; + +module.exports = Message; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/metrics.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/metrics.js new file mode 100644 index 0000000000000000000000000000000000000000..7fab7681f387e3cd2347189edbc7681ce5b2b8a9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/metrics.js @@ -0,0 +1,67 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * Job Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Metrics = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +Metrics.path = 'metrics'; + +/** + * Query for jobs that fulfill given parameters. + * @param {Object} params + * @param {String} [params.name] + * @param {String} [params.startDate] + * @param {String} [params.endDate] + * @param {Function} done + */ +Metrics.sum = function(params, done) { + var path = this.path + '/' + params.name + '/sum'; + delete params.name; + + return this.http.get(path, {data: params, done: done}); +}; + +/** + * Retrieves a list of metrics, aggregated for a given interval. + * @param {Object} params + * @param {String} params.name The name of the metric. Supported names: activity-instance-end, job-acquisition-attempt, job-acquired-success, job-acquired-failure, job-execution-rejected, job-successful, job-failed, job-locked-exclusive, executed-decision-elements + * @param {String} [params.reporter] The name of the reporter (host), on which the metrics was logged. + * @param {String} [params.startDate] The start date (inclusive). + * @param {String} [params.endDate] The end date (exclusive). + * @param {Integer} [params.firstResult] The index of the first result, used for paging. + * @param {Integer} [params.maxResults] The maximum result size of the list which should be returned. The maxResults can't be set larger than 200. Default: 200 + * @param {Integer} [params.interval] The interval for which the metrics should be aggregated. Time unit is seconds. Default: The interval is set to 15 minutes (900 seconds). + * @param {Function} done + */ +Metrics.byInterval = function(params, done) { + return this.http.get(this.path, {data: params, done: done}); +}; + +module.exports = Metrics; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/migration.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/migration.js new file mode 100644 index 0000000000000000000000000000000000000000..993cfe41f6f4b5474a7414e0db7973562c8fd5f8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/migration.js @@ -0,0 +1,93 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * Migration Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Migration = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +Migration.path = 'migration'; + +/** + * Generate a migration plan for a given source and target process definition + * @param {Object} params + * @param {String} [params.sourceProcessDefinitionId] + * @param {String} [params.targetProcessDefinitionId] + * @param {Function} done + */ +Migration.generate = function(params, done) { + var path = this.path + '/generate'; + + return this.http.post(path, { + data: params, + done: done + }); +}; + +/** + * Execute a migration plan + * @param {Object} params + * @param {String} [params.migrationPlan] + * @param {String} [params.processInstanceIds] + * @param {Function} done + */ +Migration.execute = function(params, done) { + var path = this.path + '/execute'; + + return this.http.post(path, { + data: params, + done: done + }); +}; + +/** + * Execute a migration plan asynchronously + * @param {Object} params + * @param {String} [params.migrationPlan] + * @param {String} [params.processInstanceIds] + * @param {Function} done + */ +Migration.executeAsync = function(params, done) { + var path = this.path + '/executeAsync'; + + return this.http.post(path, { + data: params, + done: done + }); +}; + +Migration.validate = function(params, done) { + var path = this.path + '/validate'; + + return this.http.post(path, { + data: params, + done: done + }); +}; + +module.exports = Migration; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/modification.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/modification.js new file mode 100644 index 0000000000000000000000000000000000000000..bad5190b0ecc6e1959db4d547a241f3e8bba934e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/modification.js @@ -0,0 +1,78 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * Modification Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Modification = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +Modification.path = 'modification'; + +/** + * Execute a modification + * @param {Object} params + * @param {String} [params.processDefinitionId] + * @param {String} [params.skipCustomListeners] + * @param {String} [params.skipIoMappings] + * @param {String} [params.processInstanceIds] + * @param {String} [params.processInstanceQuery] + * @param {String} [params.instructions] + * @param {String} [params.annotation] + * @param {Function} done + */ +Modification.execute = function(params, done) { + var path = this.path + '/execute'; + + return this.http.post(path, { + data: params, + done: done + }); +}; + +/** + * Execute a modification asynchronously + * @param {Object} params + * @param {String} [params.processDefinitionId] + * @param {String} [params.skipCustomListeners] + * @param {String} [params.skipIoMappings] + * @param {String} [params.processInstanceIds] + * @param {String} [params.processInstanceQuery] + * @param {String} [params.instructions] + * @param {String} [params.annotation] + * @param {Function} done + */ +Modification.executeAsync = function(params, done) { + var path = this.path + '/executeAsync'; + + return this.http.post(path, { + data: params, + done: done + }); +}; + +module.exports = Modification; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/password-policy.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/password-policy.js new file mode 100644 index 0000000000000000000000000000000000000000..d30b03358556980d0ac5d0c4d1e335fcf4bb3f84 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/password-policy.js @@ -0,0 +1,64 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * Password Policy Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var PasswordPolicy = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +PasswordPolicy.path = 'identity/password-policy'; + +/** + * Fetch the active password policy. + * + * @param {Function} done + */ +PasswordPolicy.get = function(done) { + return this.http.get(this.path, { + done: done + }); +}; + +/** + * Validate a password against the password policy + * + * @param {Object} [params] + * @param {String} [params.password] Password to be validated + * @param {Function} done + */ +PasswordPolicy.validate = function(params, done) { + if (typeof params === 'string') { + params = {password: params}; + } + return this.http.post(this.path, { + data: params, + done: done + }); +}; + +module.exports = PasswordPolicy; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/process-definition.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/process-definition.js new file mode 100644 index 0000000000000000000000000000000000000000..da0fe45bad99ac52a287ca176ddefe7b512887a2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/process-definition.js @@ -0,0 +1,496 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var Q = require('q'); +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * No-Op callback + */ +function noop() {} + +/** + * Process Definition Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var ProcessDefinition = AbstractClientResource.extend( + /** @lends CamSDK.client.resource.ProcessDefinition.prototype */ + { + /** + * Suspends the process definition instance + * + * @param {Object.} [params] + * @param {requestCallback} [done] + */ + suspend: function(params, done) { + // allows to pass only a callback + if (typeof params === 'function') { + done = params; + params = {}; + } + params = params || {}; + done = done || noop; + + return this.http.post(this.path, { + done: done + }); + }, + + /** + * Retrieves the statistics of a process definition. + * + * @param {Function} [done] + */ + stats: function(done) { + return this.http.post(this.path, { + done: done || noop + }); + }, + + /** + * Retrieves the BPMN 2.0 XML document of a process definition. + * + * @param {Function} [done] + */ + // xml: function(id, done) { + // return this.http.post(this.path + +'/xml', { + // done: done || noop + // }); + // }, + + /** + * Starts a process instance from a process definition. + * + * @param {Object} [varname] + * @param {Function} [done] + */ + start: function(done) { + return this.http.post(this.path, { + data: {}, + done: done + }); + } + }, + /** @lends CamSDK.client.resource.ProcessDefinition */ + { + /** + * API path for the process instance resource + */ + path: 'process-definition', + + /** + * Retrieve a single process definition + * + * @param {uuid} id of the process definition to be requested + * @param {Function} done + */ + get: function(id, done) { + // var pointer = ''; + // if (data.key) { + // pointer = 'key/'+ data.key; + // } + // else if (data.id) { + // pointer = data.id; + // } + + return this.http.get(this.path + '/' + id, { + done: done + }); + }, + + /** + * Retrieve a single process definition + * + * @param {String} key of the process definition to be requested + * @param {Function} done + */ + getByKey: function(key, done) { + return this.http.get(this.path + '/key/' + key, { + done: done + }); + }, + + /** + * Get a list of process definitions + * @param {Object} params Query parameters as follow + * @param {String} [params.name] Filter by name. + * @param {String} [params.nameLike] Filter by names that the parameter is a substring of. + * @param {String} [params.deploymentId] Filter by the deployment the id belongs to. + * @param {String} [params.key] Filter by key, i.e. the id in the BPMN 2.0 XML. Exact match. + * @param {String} [params.keyLike] Filter by keys that the parameter is a substring of. + * @param {String} [params.category] Filter by category. Exact match. + * @param {String} [params.categoryLike] Filter by categories that the parameter is a substring of. + * @param {String} [params.ver] Filter by version. + * @param {String} [params.latest] Only include those process definitions that are latest versions. + * Values may be "true" or "false". + * @param {String} [params.resourceName] Filter by the name of the process definition resource. Exact match. + * @param {String} [params.resourceNameLike] Filter by names of those process definition resources that the parameter is a substring of. + * @param {String} [params.startableBy] Filter by a user name who is allowed to start the process. + * @param {String} [params.active] Only include active process definitions. + * Values may be "true" or "false". + * @param {String} [params.suspended] Only include suspended process definitions. + * Values may be "true" or "false". + * @param {String} [params.incidentId] Filter by the incident id. + * @param {String} [params.incidentType] Filter by the incident type. + * @param {String} [params.incidentMessage] Filter by the incident message. Exact match. + * @param {String} [params.incidentMessageLike] Filter by the incident message that the parameter is a substring of. + * + * @param {String} [params.sortBy] Sort the results lexicographically by a given criterion. + * Valid values are category, "key", "id", "name", "version" and "deploymentId". + * Must be used in conjunction with the "sortOrder" parameter. + * + * @param {String} [params.sortOrder] Sort the results in a given order. + * Values may be asc for ascending "order" or "desc" for descending order. + * Must be used in conjunction with the sortBy parameter. + * + * @param {Integer} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {Integer} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. + * Will return less results, if there are no more results left. + + * @param {requestCallback} [done] + * + * @example + * CamSDK.resource('process-definition').list({ + * nameLike: 'Process' + * }, function(err, results) { + * // + * }); + */ + list: function() { + return AbstractClientResource.list.apply(this, arguments); + }, + + /** + * Get a count of process definitions + * Same parameters as list + */ + count: function() { + return AbstractClientResource.count.apply(this, arguments); + }, + + /** + * Fetch the variables of a process definition + * @param {Object.} data + * @param {String} [data.id] of the process + * @param {String} [data.key] of the process + * @param {Array} [data.names] of variables to be fetched + * @param {Function} [done] + */ + formVariables: function(data, done) { + var pointer = ''; + done = done || noop; + if (data.key) { + pointer = 'key/' + data.key; + } else if (data.id) { + pointer = data.id; + } else { + var err = new Error( + 'Process definition task variables needs either a key or an id.' + ); + done(err); + return Q.reject(err); + } + + var queryData = { + deserializeValues: data.deserializeValues + }; + + if (data.names) { + queryData.variableNames = (data.names || []).join(','); + } + + return this.http.get(this.path + '/' + pointer + '/form-variables', { + data: queryData, + done: done + }); + }, + + /** + * Submit a form to start a process definition + * + * @param {Object.} data + * @param {String} [data.key] start the process-definition with this key + * @param {String} [data.tenantId] and the this tenant-id + * @param {String} [data.id] or: start the process-definition with this id + * @param {String} [data.businessKey] of the process to be set + * @param {Array} [data.variables] variables to be set + * @param {Function} [done] + */ + submitForm: function(data, done) { + var pointer = ''; + done = done || noop; + if (data.key) { + pointer = 'key/' + data.key; + if (data.tenantId) { + pointer += '/tenant-id/' + data.tenantId; + } + } else if (data.id) { + pointer = data.id; + } else { + return done( + new Error( + 'Process definition task variables needs either a key or an id.' + ) + ); + } + + return this.http.post(this.path + '/' + pointer + '/submit-form', { + data: { + businessKey: data.businessKey, + variables: data.variables + }, + done: done + }); + }, + + /** + * Delete multiple process definitions by key or a single process definition by id + * + * @param {Object.} data + * @param {String} [data.key] delete the process-definition with this key + * @param {String} [data.tenantId] and the this tenant-id + * @param {String} [data.id] or: delete the process-definition with this id + * @param {Boolean} [data.cascade] All instances, including historic instances, + * will also be deleted + * @param {Boolean} [data.skipCustomListeners] Skip execution listener invocation for + * activities that are started or ended + * as part of this request. + * @param {Function} [done] + */ + delete: function(data, done) { + done = done || noop; + + var pointer = ''; + if (data.key) { + pointer = 'key/' + data.key; + if (data.tenantId) { + pointer += '/tenant-id/' + data.tenantId; + } + pointer += '/delete'; + } else if (data.id) { + pointer = data.id; + } else { + return done( + new Error('Process definition deletion needs either a key or an id.') + ); + } + + var queryParams = '?'; + var param = 'cascade'; + if (typeof data[param] === 'boolean') { + queryParams += param + '=' + data[param]; + } + + param = 'skipCustomListeners'; + if (typeof data[param] === 'boolean') { + if (queryParams.length > 1) { + queryParams += '&'; + } + + queryParams += param + '=' + data[param]; + } + + param = 'skipIoMappings'; + if (typeof data[param] === 'boolean') { + if (queryParams.length > 1) { + queryParams += '&'; + } + + queryParams += param + '=' + data[param]; + } + + return this.http.del(this.path + '/' + pointer + queryParams, { + done: done + }); + }, + + /** + * Retrieves the form of a process definition. + * @param {Function} [done] + */ + startForm: function(data, done) { + var path = + this.path + + '/' + + (data.key ? 'key/' + data.key : data.id) + + '/startForm'; + return this.http.get(path, { + done: done || noop + }); + }, + + /** + * Retrieves the form of a process definition. + * @param {Function} [done] + */ + xml: function(data, done) { + var path = + this.path + '/' + (data.id ? data.id : 'key/' + data.key) + '/xml'; + return this.http.get(path, { + done: done || noop + }); + }, + + /** + * Retrieves runtime statistics of a given process definition grouped by activities + * @param {Function} [done] + */ + statistics: function(data, done) { + var path = this.path; + + if (data.id) { + path += '/' + data.id; + } else if (data.key) { + path += '/key/' + data.key; + } + + path += '/statistics'; + + return this.http.get(path, { + data: data, + done: done || noop + }); + }, + + /** + * Submits the form of a process definition. + * + * @param {Object} [data] + * @param {Function} [done] + */ + submit: function(data, done) { + var path = this.path; + if (data.key) { + path += '/key/' + data.key; + } else { + path += '/' + data.id; + } + path += '/submit-form'; + + return this.http.post(path, { + data: data, + done: done + }); + }, + + /** + * Suspends one or more process definitions + * + * @param {String|String[]} ids + * @param {Object.} [params] + * @param {requestCallback} [done] + */ + suspend: function(ids, params, done) { + // allows to pass only a callback + if (typeof params === 'function') { + done = params; + params = {}; + } + params = params || {}; + done = done || noop; + // allows to pass a single ID + ids = Array.isArray(ids) ? ids : [ids]; + + return this.http.post(this.path, { + done: done + }); + }, + + /** + * Instantiates a given process definition. + * + * @param {Object} [params] + * @param {String} [params.id] The id of the process definition to be instantiated. Must be omitted if key is provided. + * @param {String} [params.key] The key of the process definition (the latest version thereof) to be instantiated. Must be omitted if id is provided. + * @param {String} [params.tenantId] The id of the tenant the process definition belongs to. Must be omitted if id is provided. + * @param {String} [params.variables] A JSON object containing the variables the process is to be initialized with. Each key corresponds to a variable name and each value to a variable value. + * @param {String} [params.businessKey] The business key the process instance is to be initialized with. The business key uniquely identifies the process instance in the context of the given process definition. + * @param {String} [params.caseInstanceId] The case instance id the process instance is to be initialized with. + */ + start: function(params, done) { + var url = this.path + '/'; + + if (params.id) { + url = url + params.id; + } else { + url = url + 'key/' + params.key; + + if (params.tenantId) { + url = url + '/tenant-id/' + params.tenantId; + } + } + + return this.http.post(url + '/start', { + data: params, + done: done + }); + }, + + /** + * Instantiates a given process definition. + + * @param {String} [id] The id of the process definition to activate or suspend. + * @param {Object} [params] + * @param {Number} [params.historyTimeToLive] New value for historyTimeToLive field of process definition. Can be null. + */ + updateHistoryTimeToLive: function(id, params, done) { + var url = this.path + '/' + id + '/history-time-to-live'; + + return this.http.put(url, { + data: params, + done: done + }); + }, + + restart: function(id, params, done) { + var url = this.path + '/' + id + '/restart'; + + return this.http.post(url, { + data: params, + done: done + }); + }, + + restartAsync: function(id, params, done) { + var url = this.path + '/' + id + '/restart-async'; + + return this.http.post(url, { + data: params, + done: done + }); + }, + + /** + * For the given process, returns a list of statically referenced called process definitions + * @param {uuid} id of the process definition to be requested + * @param {requestCallback} [done] + */ + staticCalledProcessDefinitions: function(id, done) { + const path = `${this.path}/${id}/static-called-process-definitions`; + + return this.http.get(path, { + done: done + }); + } + } +); + +module.exports = ProcessDefinition; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/process-instance.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/process-instance.js new file mode 100644 index 0000000000000000000000000000000000000000..6a8342df2e57521373ab6098a83073a1f896331d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/process-instance.js @@ -0,0 +1,262 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); +var utils = require('../../utils'); + +/** + * Process Instance Resource + * + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var ProcessInstance = AbstractClientResource.extend( + /** @lends CamSDK.client.resource.ProcessInstance.prototype */ + {}, + + /** @lends CamSDK.client.resource.ProcessInstance */ + { + /** + * API path for the process instance resource + */ + path: 'process-instance', + + /** + * Retrieve a single process instance + * + * @param {uuid} id of the process instance to be requested + * @param {Function} done + */ + get: function(id, done) { + return this.http.get(this.path + '/' + id, { + done: done + }); + }, + + /** + * Creates a process instance from a process definition + * + * @param {Object} params + * @param {String} [params.id] + * @param {String} [params.key] + * @param {Object.} [params.variables] + * @param {requestCallback} [done] + */ + create: function(params, done) { + return this.http.post(params, done); + }, + + list: function(params, done) { + var path = this.path; + + // those parameters have to be passed in the query and not body + path += '?firstResult=' + (params.firstResult || 0); + path += '&maxResults=' + (params.maxResults || 15); + + return this.http.post(path, { + data: params, + done: done + }); + }, + + count: function(params, done) { + var path = this.path + '/count'; + + return this.http.post(path, { + data: params, + done: done + }); + }, + + getActivityInstances: function(id, done) { + return this.http.get(this.path + '/' + id + '/activity-instances', { + done: done + }); + }, + + /** + * Post process instance modifications + * @see http://docs.camunda.org/api-references/rest/#process-instance-modify-process-instance-execution-state-method + * + * @param {Object} params + * @param {UUID} params.id process instance UUID + * + * @param {Array} params.instructions Array of instructions + * + * @param {Boolean} [params.skipCustomListeners] Skip execution listener invocation for + * activities that are started or ended + * as part of this request. + * + * @param {Boolean} [params.skipIoMappings] Skip execution of input/output + * variable mappings for activities that + * are started or ended as part of + * this request. + * + * @param {String} [params.annotation] Add Annotation to the user operation log + * + * @param {requestCallback} done + */ + modify: function(params, done) { + return this.http.post(this.path + '/' + params.id + '/modification', { + data: params, + done: done + }); + }, + + modifyAsync: function(params, done) { + return this.http.post( + this.path + '/' + params.id + '/modification-async', + { + data: params, + done: done + } + ); + }, + + /** + * Delete multiple process instances asynchronously (batch). + * + * @see https://docs.camunda.org/manual/latest/reference/rest/process-instance/post-delete/ + * + * @param {Object} payload + * @param {requestCallback} done + * + */ + deleteAsync: function(payload, done) { + return this.http.post(this.path + '/delete', { + data: payload, + done: done + }); + }, + + /** + * Delete a set of process instances asynchronously (batch) based on a historic process instance query. + * + * @see https://docs.camunda.org/manual/latest/reference/rest/process-instance/post-delete-historic-query-based/ + * + * @param {Object} payload + * @param {requestCallback} done + * + */ + deleteAsyncHistoricQueryBased: function(payload, done) { + return this.http.post(this.path + '/delete-historic-query-based', { + data: payload, + done: done + }); + }, + + /** + * Set retries of jobs belonging to process instances asynchronously (batch). + * + * @see https://docs.camunda.org/manual/latest/reference/rest/process-instance/post-set-job-retries + * + * @param {Object} payload + * @param {requestCallback} done + * + */ + setJobsRetriesAsync: function(payload, done) { + return this.http.post(this.path + '/job-retries', { + data: payload, + done: done + }); + }, + + /** + * Create a batch to set retries of jobs asynchronously based on a historic process instance query. + * + * @see https://docs.camunda.org/manual/latest/reference/rest/process-instance/post-set-job-retries-historic-query-based + * + * @param {Object} payload + * @param {requestCallback} done + * + */ + setJobsRetriesAsyncHistoricQueryBased: function(payload, done) { + return this.http.post(this.path + '/job-retries-historic-query-based', { + data: payload, + done: done + }); + }, + + /** + * Activates or suspends process instances asynchronously with a list of process instance ids, a process instance query, and/or a historical process instance query + * + * @see https://docs.camunda.org/manual/latest/reference/rest/process-instance/post-activate-suspend-in-batch/ + * + * @param {Object} payload + * @param {requestCallback} done + */ + suspendAsync: function(payload, done) { + return this.http.post(this.path + '/suspended-async', { + data: payload, + done: done + }); + }, + + /** + * Sets variables to process instances (batch). + * + * @see https://docs.camunda.org/manual/latest/reference/rest/process-instance/post-set-variables-async/ + * + * @param {Object} payload + * @param {requestCallback} done + */ + setVariablesAsync: function(payload, done) { + return this.http.post(this.path + '/variables-async', { + data: payload, + done: done + }); + }, + + /** + * Correlates a message against process instances (batch). + * + * @see https://docs.camunda.org/manual/latest/reference/rest/process-instance/post-message-async/ + * + * @param {Object} payload + * @param {requestCallback} done + */ + correlateMessageAsync: function(payload, done) { + return this.http.post(this.path + '/message-async', { + data: payload, + done: done + }); + }, + + /** + * Sets a variable of a given process instance by id. + * + * @see http://docs.camunda.org/manual/develop/reference/rest/process-instance/variables/put-variable/ + * + * @param {uuid} id + * @param {Object} params + * @param {requestCallback} done + */ + setVariable: function(id, params, done) { + var url = + this.path + '/' + id + '/variables/' + utils.escapeUrl(params.name); + return this.http.put(url, { + data: params, + done: done + }); + } + } +); + +module.exports = ProcessInstance; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/task-identity-link.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/task-identity-link.js new file mode 100644 index 0000000000000000000000000000000000000000..97d81f2b761892832c02de30b38a9ee6199a6881 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/task-identity-link.js @@ -0,0 +1,30 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * Task identity link resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var TaskIdentityLink = AbstractClientResource.extend(); + +module.exports = TaskIdentityLink; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/task-report.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/task-report.js new file mode 100644 index 0000000000000000000000000000000000000000..e6d2848842e345b9ae29fac9d9ed0b205c5cf3ee --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/task-report.js @@ -0,0 +1,64 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * Task Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var TaskReport = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +TaskReport.path = 'task/report'; + +/** + * Fetch the count of tasks grouped by candidate group. + * + * @param {Function} done + */ +TaskReport.countByCandidateGroup = function(done) { + return this.http.get(this.path + '/candidate-group-count', { + done: done + }); +}; + +/** + * Query for process instance durations report. + * @param {Object} [params] + * @param {Object} [params.reportType] Must be 'duration'. + * @param {Object} [params.periodUnit] Can be one of `month` or `quarter`, defaults to `month` + * @param {Object} [params.processDefinitionIn] Comma separated list of process definition IDs + * @param {Object} [params.startedAfter] Date after which the process instance were started + * @param {Object} [params.startedBefore] Date before which the process instance were started + * @param {Function} done + */ +TaskReport.countByCandidateGroupAsCsv = function(done) { + return this.http.get(this.path + '/candidate-group-count', { + accept: 'text/csv', + done: done + }); +}; + +module.exports = TaskReport; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/task.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/task.js new file mode 100644 index 0000000000000000000000000000000000000000..d26ed108d1d2fe448232081dc86046a9f2c39d40 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/task.js @@ -0,0 +1,594 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var Q = require('q'); +var AbstractClientResource = require('./../abstract-client-resource'); +var utils = require('../../utils'); + +/** + * No-Op callback + */ +function noop() {} + +/** + * Task Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Task = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +Task.path = 'task'; + +/** + * Fetch a list of tasks + * @param {Object} [params] + * @param {String} [params.processInstanceId] Restrict to tasks that belong to process instances with the given id. + * @param {String} [params.processInstanceBusinessKey] Restrict to tasks that belong to process instances with the given business key. + * @param {String} [params.processInstanceBusinessKeyLike] Restrict to tasks that have a process instance business key that has the parameter value as a substring. + * @param {String} [params.processDefinitionId] Restrict to tasks that belong to a process definition with the given id. + * @param {String} [params.processDefinitionKey] Restrict to tasks that belong to a process definition with the given key. + * @param {String} [params.processDefinitionName] Restrict to tasks that belong to a process definition with the given name. + * @param {String} [params.processDefinitionNameLike] Restrict to tasks that have a process definition name that has the parameter value as a substring. + * @param {String} [params.executionId] Restrict to tasks that belong to an execution with the given id. + * @param {String} [params.activityInstanceIdIn] Only include tasks which belongs to one of the passed and comma-separated activity instance ids. + * @param {String} [params.assignee] Restrict to tasks that the given user is assigned to. + * @param {String} [params.assigneeLike] Restrict to tasks that have an assignee that has the parameter value as a substring. + * @param {String} [params.owner] Restrict to tasks that the given user owns. + * @param {String} [params.candidateGroup] Only include tasks that are offered to the given group. + * @param {String} [params.candidateUser] Only include tasks that are offered to the given user. + * @param {String} [params.involvedUser] Only include tasks that the given user is involved in. + * A user is involved in a task if there exists an identity link between task and user (e.g. the user is the assignee). + * @param {String} [params.unassigned] If set to true, restricts the query to all tasks that are unassigned. + * @param {String} [params.taskDefinitionKey] Restrict to tasks that have the given key. + * @param {String} [params.taskDefinitionKeyLike] Restrict to tasks that have a key that has the parameter value as a substring. + * @param {String} [params.name] Restrict to tasks that have the given name. + * @param {String} [params.nameLike] Restrict to tasks that have a name with the given parameter value as substring. + * @param {String} [params.description] Restrict to tasks that have the given description. + * @param {String} [params.descriptionLike] Restrict to tasks that have a description that has the parameter value as a substring. + * @param {String} [params.priority] Restrict to tasks that have the given priority. + * @param {String} [params.maxPriority] Restrict to tasks that have a lower or equal priority. + * @param {String} [params.minPriority] Restrict to tasks that have a higher or equal priority. + * @param {String} [params.due] Restrict to tasks that are due on the given date. + * The date must have the format yyyy-MM-dd'T'HH:mm:ss, so for example 2013-01-23T14:42:45 is valid. + * @param {String} [params.dueAfter] Restrict to tasks that are due after the given date. + * The date must have the format yyyy-MM-dd'T'HH:mm:ss, so for example 2013-01-23T14:42:45 is valid. + * @param {String} [params.dueBefore] Restrict to tasks that are due before the given date. + * The date must have the format yyyy-MM-dd'T'HH:mm:ss, so for example 2013-01-23T14:42:45 is valid. + * @param {String} [params.followUp] Restrict to tasks that have a followUp date on the given date. + * The date must have the format yyyy-MM-dd'T'HH:mm:ss, so for example 2013-01-23T14:42:45 is valid. + * @param {String} [params.followUpAfter] Restrict to tasks that have a followUp date after the given date. + * The date must have the format yyyy-MM-dd'T'HH:mm:ss, so for example 2013-01-23T14:42:45 is valid. + * @param {String} [params.followUpBefore] Restrict to tasks that have a followUp date before the given date. + * The date must have the format yyyy-MM-dd'T'HH:mm:ss, so for example 2013-01-23T14:42:45 is valid. + * @param {String} [params.created] Restrict to tasks that were created on the given date. + * The date must have the format yyyy-MM-dd'T'HH:mm:ss, so for example 2013-01-23T14:42:45 is valid. + * @param {String} [params.createdAfter] Restrict to tasks that were created after the given date. + * The date must have the format yyyy-MM-dd'T'HH:mm:ss, so for example 2013-01-23T14:42:45 is valid. + * @param {String} [params.createdBefore] Restrict to tasks that were created before the given date. + * The date must have the format yyyy-MM-dd'T'HH:mm:ss, so for example 2013-01-23T14:42:45 is valid. + * @param {String} [params.delegationState] Restrict to tasks that are in the given delegation state. + * Valid values are "PENDING" and "RESOLVED". + * @param {String} [params.candidateGroups] Restrict to tasks that are offered to any of the given candidate groups. Takes a comma-separated list of group names, so for example developers,support,sales. + * @param {String} [params.active] Only include active tasks. Values may be true or false. suspended Only include suspended tasks. + * Values may be "true" or "false". + * @param {String} [params.taskVariables] Only include tasks that have variables with certain values. Variable tasking expressions are comma-separated and are structured as follows: + * A valid parameter value has the form key_operator_value. key is the variable name, op is the comparison operator to be used and value the variable value. Note: Values are always treated as String objects on server side. Valid operator values are: eq - equals; neq - not equals; gt - greater than; gteq - greater than or equals; lt - lower than; lteq - lower than or equals; like. key and value may not contain underscore or comma characters. + * @param {String} [params.processVariables] Only include tasks that belong to process instances that have variables with certain values. + * Variable tasking expressions are comma-separated and are structured as follows: + * A valid parameter value has the form key_operator_value. "key" is the variable name, "op" is the comparison operator to be used and value the variable value. + * Note: Values are always treated as String objects on server side. + * Valid operator values are: "eq" - equals; "neq" - not equals; "gt" - greater than; "gteq" - greater than or equals; "lt" - lower than; "lteq" - lower than or equals; like. + * "key" and "value" may not contain underscore or comma characters. + * + * @param {String} [params.sortBy] Sort the results lexicographically by a given criterion. + * Valid values are "instanceId", "dueDate", "executionId", "assignee", "created", "description", "id", "name" and "priority". + * Must be used in conjunction with the sortOrder parameter. + * @param {String} [params.sortOrder] Sort the results in a given order. Values may be "asc" for ascending order or "desc" for descending order. + * Must be used in conjunction with the sortBy parameter. + * + * @param {String} [params.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {String} [params.maxResults] Pagination of results. Specifies the maximum number of results to return. + * Will return less results, if there are no more results left. + * @param {Function} done + */ +Task.list = function(params, done) { + done = done || noop; + var deferred = Q.defer(); + + this.http.get(this.path, { + data: params, + done: function(err, data) { + if (err) { + done(err); + return deferred.reject(err); + } + + if (data._embedded) { + // to ease the use of task data, we compile them here + var tasks = data._embedded.task || data._embedded.tasks; + var procDefs = data._embedded.processDefinition; + + for (var t in tasks) { + var task = tasks[t]; + task._embedded = task._embedded || {}; + for (var p in procDefs) { + if (procDefs[p].id === task.processDefinitionId) { + task._embedded.processDefinition = [procDefs[p]]; + break; + } + } + } + } + + done(null, data); + deferred.resolve(data); + } + }); + + return deferred.promise; +}; + +/** + * Retrieve a single task + * @param {uuid} taskId of the task to be requested + * @param {Function} done + */ +Task.get = function(taskId, done) { + return this.http.get(this.path + '/' + taskId, { + done: done + }); +}; + +/** + * Retrieve the comments for a single task + * @param {uuid} taskId of the task for which the comments are requested + * @param {Function} done + */ +Task.comments = function(taskId, done) { + return this.http.get(this.path + '/' + taskId + '/comment', { + done: done + }); +}; + +/** + * Retrieve the identity links for a single task + * @param {uuid} taskId of the task for which the identity links are requested + * @param {Function} done + */ +Task.identityLinks = function(taskId, done) { + return this.http.get(this.path + '/' + taskId + '/identity-links', { + done: done + }); +}; + +/** + * Add an identity link to a task + * @param {uuid} taskId of the task for which the identity link is created + * @param {Object} [params] + * @param {String} [params.userId] The id of the user to link to the task. If you set this parameter, you have to omit groupId + * @param {String} [params.groupId] The id of the group to link to the task. If you set this parameter, you have to omit userId + * @param {String} [params.type] Sets the type of the link. Must be provided + * @param {Function} done + */ +Task.identityLinksAdd = function(taskId, params, done) { + if (arguments.length === 2) { + done = arguments[1]; + params = arguments[0]; + taskId = params.id; + } + return this.http.post(this.path + '/' + taskId + '/identity-links', { + data: params, + done: done + }); +}; + +/** + * Removes an identity link from a task. + * @param {uuid} taskId The id of the task to remove a link from + * @param {Object} [params] + * @param {String} [params.userId] The id of the user being part of the link. If you set this parameter, you have to omit groupId. + * @param {String} [params.groupId] The id of the group being part of the link. If you set this parameter, you have to omit userId. + * @param {String} [params.type] Specifies the type of the link. Must be provided. + * @param {Function} done + */ +Task.identityLinksDelete = function(taskId, params, done) { + if (arguments.length === 2) { + done = arguments[1]; + params = arguments[0]; + taskId = params.id; + } + + return this.http.post(this.path + '/' + taskId + '/identity-links/delete', { + data: params, + done: done + }); +}; + +/** + * Create a comment for a task. + * + * @param {String} taskId The id of the task to add the comment to. + * @param {Object} [params] + * @param {String} [params.message] The message of the task comment to create. + * @param {String} [params.processInstanceId] The id of the process instance the comment is related to. + * @param {Function} done + */ +Task.createComment = function(taskId, params, done) { + return this.http.post(this.path + '/' + taskId + '/comment/create', { + data: typeof params === 'string' ? {message: params} : params, + done: done + }); +}; + +/** + * Creates a task + * + * @param {Object} task is an object representation of a task + * @param {Function} done + */ +Task.create = function(task, done) { + return this.http.post(this.path + '/create', { + data: task, + done: done + }); +}; + +/** + * Update a task + * + * @param {Object} task is an object representation of a task + * @param {Function} done + */ +Task.update = function(task, done) { + return this.http.put(this.path + '/' + task.id, { + data: task, + done: done + }); +}; + +// /** +// * Save a task +// * +// * @see Task.create +// * @see Task.update +// * +// * @param {Object} task is an object representation of a task, if it has +// * an id property, the task will be updated, otherwise created +// * @param {Function} done +// */ +// Task.save = function(task, done) { +// return Task[task.id ? 'update' : 'create'](task, done); +// }; + +/** + * Change the assignee of a task to a specific user. + * + * Note: The difference with claim a task is that + * this method does not check if the task already has a user assigned to it + * + * Note: The response of this call is empty. + * + * @param {String} taskId + * @param {String} userId + * @param {Function} done + */ +Task.assignee = function(taskId, userId, done) { + var data = { + userId: userId + }; + + if (arguments.length === 2) { + taskId = arguments[0].taskId; + data.userId = arguments[0].userId; + done = arguments[1]; + } + + return this.http.post(this.path + '/' + taskId + '/assignee', { + data: data, + done: done + }); +}; + +/** + * Delegate a task to another user. + * + * Note: The response of this call is empty. + * + * @param {String} taskId + * @param {String} userId + * @param {Function} done + */ +Task.delegate = function(taskId, userId, done) { + var data = { + userId: userId + }; + + if (arguments.length === 2) { + taskId = arguments[0].taskId; + data.userId = arguments[0].userId; + done = arguments[1]; + } + + return this.http.post(this.path + '/' + taskId + '/delegate', { + data: data, + done: done + }); +}; + +/** + * Claim a task for a specific user. + * + * Note: The difference with set a assignee is that + * here a check is performed to see if the task already has a user assigned to it. + * + * Note: The response of this call is empty. + * + * @param {String} taskId + * @param {String} userId + * @param {Function} done + */ +Task.claim = function(taskId, userId, done) { + var data = { + userId: userId + }; + + if (arguments.length === 2) { + taskId = arguments[0].taskId; + data.userId = arguments[0].userId; + done = arguments[1]; + } + + return this.http.post(this.path + '/' + taskId + '/claim', { + data: data, + done: done + }); +}; + +/** + * Resets a task's assignee. If successful, the task is not assigned to a user. + * + * Note: The response of this call is empty. + * + * @param {String} taskId + * @param {Function} done + */ +Task.unclaim = function(taskId, done) { + if (typeof taskId !== 'string') { + taskId = taskId.taskId; + } + + return this.http.post(this.path + '/' + taskId + '/unclaim', { + done: done + }); +}; + +/** + * Complete a task and update process variables using a form submit. + * There are two difference between this method and the complete method: + * + * If the task is in state PENDING - ie. has been delegated before, + * it is not completed but resolved. Otherwise it will be completed. + * + * If the task has Form Field Metadata defined, + * the process engine will perform backend validation for any form fields which have validators defined. + * See the Generated Task Forms section of the User Guide for more information. + * + * @param {Object} data + * @param {Function} done + */ +Task.submitForm = function(data, done) { + done = done || noop; + if (!data.id) { + var err = new Error('Task submitForm needs a task id.'); + done(err); + return Q.reject(err); + } + + return this.http.post(this.path + '/' + data.id + '/submit-form', { + data: { + variables: data.variables + }, + done: done + }); +}; + +/** + * Complete a task and update process variables. + * + * @param {object} [params] + * @param {uuid} [params.id] Id of the task. This value is mandatory. + * @param {Object.} [params.variables] Process variables which need to be updated. + * @param {Function} done + */ +Task.complete = function(params, done) { + done = done || noop; + + if (!params.id) { + var err = new Error('Task complete needs a task id.'); + done(err); + return Q.reject(err); + } + + return this.http.post(this.path + '/' + params.id + '/complete', { + data: { + variables: params.variables + }, + done: done + }); +}; + +/** + * Reports an escalation in the context of a running task by id. + * + * @param {Object} [data] + * @param {uuid} [data.id] Id of the task. This value is mandatory. + * @param {String} [data.escalationCode] An escalation code that indicates the predefined escalation. This value is mandatory. + * @param {Object.} [data.variables] Process variables which need to be updated. + * @param {Function} done + */ +Task.bpmnEscalation = function(data, done) { + done = done || noop; + if (!data.id || !data.escalationCode) { + var err = new Error( + 'Task bpmnEscalation needs a task id and escalation code.' + ); + done(err); + return Q.reject(err); + } + + return this.http.post(this.path + '/' + data.id + '/bpmnEscalation', { + data: { + escalationCode: data.escalationCode, + variables: data.variables + }, + done: done + }); +}; + +/** + * Reports an error in the context of a running task by id. + * + * @param {Object} [data] + * @param {uuid} [data.id] Id of the task. This value is mandatory. + * @param {String} [data.errorCode] An error code that indicates the predefined error. This value is mandatory. + * @param {String} [data.errorMessage] An error message that describes the error. + * @param {Object.} [data.variables] Process variables which need to be updated. + * @param {Function} done + */ +Task.bpmnError = function(data, done) { + done = done || noop; + if (!data.id || !data.errorCode) { + var err = new Error('Task bpmnError needs a task id and error code.'); + done(err); + return Q.reject(err); + } + + return this.http.post(this.path + '/' + data.id + '/bpmnError', { + data: { + variables: data.variables, + errorCode: data.errorCode, + errorMessage: data.errorMessage + }, + done: done + }); +}; + +Task.formVariables = function(data, done) { + done = done || noop; + var pointer = ''; + if (data.key) { + pointer = 'key/' + data.key; + } else if (data.id) { + pointer = data.id; + } else { + var err = new Error('Task variables needs either a key or an id.'); + done(err); + return Q.reject(err); + } + + var queryData = { + deserializeValues: data.deserializeValues + }; + + if (data.names) { + queryData.variableNames = data.names.join(','); + } + + return this.http.get(this.path + '/' + pointer + '/form-variables', { + data: queryData, + done: done + }); +}; + +/** + * Retrieve the form for a single task + * @param {uuid} taskId of the task for which the form is requested + * @param {Function} done + */ +Task.form = function(taskId, done) { + return this.http.get(this.path + '/' + taskId + '/form', { + done: done + }); +}; + +/** + * Sets a variable in the context of a given task. + * @param {Object} [params] + * @param {String} [params.id] The id of the task to set the variable for. + * @param {String} [params.varId] The name of the variable to set. + * @param {String} [params.value] The variable's value. For variables of type Object, the serialized value has to be submitted as a String value. + * @param {String} [params.type] The value type of the variable. + * @param {String} [params.valueInfo] A JSON object containing additional, value-type-dependent properties. + * @param {Function} done + */ +Task.localVariable = function(params, done) { + return this.http.put( + this.path + '/' + params.id + '/localVariables/' + params.varId, + { + data: params, + done: done + } + ); +}; + +/** + * Retrieve the local variables for a single task + * @param {uuid} taskId of the task for which the variables are requested + * @param {Function} done + */ +Task.localVariables = function(taskId, done) { + return this.http.get(this.path + '/' + taskId + '/localVariables', { + done: done + }); +}; + +/** + * Updates or deletes the variables in the context of a task. + * Updates precede deletions. + * So, if a variable is updated AND deleted, the deletion overrides the update. + */ +Task.modifyVariables = function(data, done) { + return this.http.post(this.path + '/' + data.id + '/localVariables', { + data: data, + done: done + }); +}; + +/** + * Removes a local variable from a task. + */ +Task.deleteVariable = function(data, done) { + return this.http.del( + this.path + + '/' + + data.id + + '/localVariables/' + + utils.escapeUrl(data.varId), + { + done: done + } + ); +}; + +module.exports = Task; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/telemetry.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/telemetry.js new file mode 100644 index 0000000000000000000000000000000000000000..6ed55d0694755c8f4f8c7baac4144d380941cb54 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/telemetry.js @@ -0,0 +1,88 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +function noop() {} + +/** + * Telemetry Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Telemetry = AbstractClientResource.extend(); + +/** + * API path for the process definition resource + * @type {String} + */ +Telemetry.path = 'telemetry'; + +/** + * Fetches the telemetry configuration. + * + * @param {Function} done + */ +Telemetry.get = function(done) { + return this.http.get(this.path + '/configuration', { + done: done + }); +}; + +/** + * Configures whether Camunda receives data collection of the process engine setup and usage. + * + * @param {Object} payload is an object representation of an authorization + * @param {Boolean} payload.enableTelemetry Specifies if the data collection should be sent or not. + * @param {Function} done + */ +Telemetry.configure = function(payload, done) { + if (typeof payload === 'boolean') { + payload = {enableTelemetry: payload}; + } + + return this.http.post(this.path + '/configuration', { + data: payload, + done: done + }); +}; + +/** + * Fetches telemetry data for diagnostics. + * + * @param {Object} payload + * @param {Function} done + */ +Telemetry.fetchData = function(payload, done) { + if (typeof payload === 'function') { + done = payload; + payload = {}; + } + + payload = payload || {}; + done = done || noop; + + return this.http.get(this.path + '/data', { + data: payload, + done: done + }); +}; + +module.exports = Telemetry; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/tenant.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/tenant.js new file mode 100644 index 0000000000000000000000000000000000000000..ea4fe4d16873361106de2a5f622c9b125319f4c8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/tenant.js @@ -0,0 +1,271 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); +var utils = require('../../utils'); + +/** + * No-Op callback + */ +function noop() {} + +/** + * Group Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Tenant = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +Tenant.path = 'tenant'; + +/** + * Creates a tenant + * + * @param {Object} tenant is an object representation of a group + * @param {String} tenant.id + * @param {String} tenant.name + * @param {Function} done + */ +Tenant.create = function(options, done) { + return this.http.post(this.path + '/create', { + data: options, + done: done || noop + }); +}; + +/** + * Query for tenants using a list of parameters and retrieves the count + * + * @param {String} [options.id] Filter by the id of the tenant. + * @param {String} [options.name] Filter by the name of the tenant. + * @param {String} [options.nameLike] Filter by the name that the parameter is a substring of. + * @param {String} [options.userMember] Only retrieve tenants where the given user id is a member of. + * @param {String} [options.groupMember] Only retrieve tenants where the given group id is a member of. + * @param {Function} done + */ +Tenant.count = function(options, done) { + if (typeof options === 'function') { + done = options; + options = {}; + } else { + options = options || {}; + } + + return this.http.get(this.path + '/count', { + data: options, + done: done || noop + }); +}; + +/** + * Retrieves a single tenant + * + * @param {String} [options.id] The id of the tenant, can be a property (id) of an object + * @param {Function} done + */ +Tenant.get = function(options, done) { + var id; + + if (typeof options === 'string') { + id = options; + options = {}; + } else { + id = options.id; + delete options.id; + } + + return this.http.get(this.path + '/' + utils.escapeUrl(id), { + data: options, + done: done || noop + }); +}; + +/** + * Query for a list of tenants using a list of parameters. + * The size of the result set can be retrieved by using the get tenants count method + * + * @param {String} [options.id] Filter by the id of the tenant. + * @param {String} [options.name] Filter by the name of the tenant. + * @param {String} [options.nameLike] Filter by the name that the parameter is a substring of. + * @param {String} [options.userMember] Only retrieve tenants where the given user id is a member of. + * @param {String} [options.grouprMember] Only retrieve tenants where the given group id is a member of. + * @param {String} [options.sortBy] Sort the results lexicographically by a given criterion. + * Valid values are id and name. + * Must be used in conjunction with the sortOrder parameter. + * @param {String} [options.sortOrder] Sort the results in a given order. + * Values may be asc for ascending order or desc for descending order. + * Must be used in conjunction with the sortBy parameter. + * @param {String} [options.firstResult] Pagination of results. + * Specifies the index of the first result to return. + * @param {String} [options.maxResults] Pagination of results. + * Specifies the maximum number of results to return. + * Will return less results if there are no more results left. + * + * @param {Function} done + */ +Tenant.list = function(options, done) { + if (typeof options === 'function') { + done = options; + options = {}; + } else { + options = options || {}; + } + + return this.http.get(this.path, { + data: options, + done: done || noop + }); +}; + +/** + * Add a user member to a tenant + * + * @param {String} [options.id] The id of the tenant + * @param {String} [options.userId] The id of user to add to the tenant + * @param {Function} done + */ +Tenant.createUserMember = function(options, done) { + return this.http.put( + this.path + + '/' + + utils.escapeUrl(options.id) + + '/user-members/' + + utils.escapeUrl(options.userId), + { + data: options, + done: done || noop + } + ); +}; + +/** + * Add a group member to a tenant + * + * @param {String} [options.id] The id of the tenant + * @param {String} [options.groupId] The id of group to add to the tenant + * @param {Function} done + */ +Tenant.createGroupMember = function(options, done) { + return this.http.put( + this.path + + '/' + + utils.escapeUrl(options.id) + + '/group-members/' + + utils.escapeUrl(options.groupId), + { + data: options, + done: done || noop + } + ); +}; + +/** + * Removes a user member of a tenant + * + * @param {String} [options.id] The id of the tenant + * @param {String} [options.userId] The id of user to add to the tenant + * @param {Function} done + */ +Tenant.deleteUserMember = function(options, done) { + return this.http.del( + this.path + + '/' + + utils.escapeUrl(options.id) + + '/user-members/' + + utils.escapeUrl(options.userId), + { + data: options, + done: done || noop + } + ); +}; + +/** + * Removes a group member of a Tenant + * + * @param {String} [options.id] The id of the tenant + * @param {String} [options.groupId] The id of group to add to the tenant + * @param {Function} done + */ +Tenant.deleteGroupMember = function(options, done) { + return this.http.del( + this.path + + '/' + + utils.escapeUrl(options.id) + + '/group-members/' + + utils.escapeUrl(options.groupId), + { + data: options, + done: done || noop + } + ); +}; + +/** + * Update a tenant + * + * @param {Object} tenant is an object representation of a tenant + * @param {Function} done + */ +Tenant.update = function(options, done) { + return this.http.put(this.path + '/' + utils.escapeUrl(options.id), { + data: options, + done: done || noop + }); +}; + +/** + * Delete a tenant + * + * @param {Object} tenant is an object representation of a tenant + * @param {Function} done + */ +Tenant.delete = function(options, done) { + return this.http.del(this.path + '/' + utils.escapeUrl(options.id), { + data: options, + done: done || noop + }); +}; + +Tenant.options = function(options, done) { + var id; + + if (typeof options === 'function') { + done = options; + id = ''; + } else { + id = typeof options === 'string' ? options : options.id; + if (id === undefined) { + id = ''; + } + } + + return this.http.options(this.path + '/' + utils.escapeUrl(id), { + done: done || noop, + headers: { + Accept: 'application/json' + } + }); +}; +module.exports = Tenant; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/user.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/user.js new file mode 100644 index 0000000000000000000000000000000000000000..32e733b3be41e26dff762c29fcb8e61cb47dfd01 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/user.js @@ -0,0 +1,283 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var Q = require('q'); +var AbstractClientResource = require('./../abstract-client-resource'); +var utils = require('../../utils'); + +/** + * No-Op callback + */ +function noop() {} + +/** + * User Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var User = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +User.path = 'user'; + +/** + * Check resource access + * @param {Object} options + * @param {String} options.id + * @param {Function} done + */ +User.options = function(options, done) { + var id; + + if (typeof options === 'function') { + done = options; + id = ''; + } else { + id = typeof options === 'string' ? options : options.id; + if (id === undefined) { + id = ''; + } + } + + return this.http.options(this.path + '/' + utils.escapeUrl(id), { + done: done || noop, + headers: { + Accept: 'application/json' + } + }); +}; + +/** + * Creates a user + * @param {Object} options + * @param {String} options.id + * @param {String} options.password + * @param {String} options.firstName + * @param {String} options.lastName + * @param {String} [options.email] + * @param {Function} done + */ +User.create = function(options, done) { + options = options || {}; + done = done || noop; + + var required = ['id', 'firstName', 'lastName', 'password']; + for (var r in required) { + var name = required[r]; + if (!options[name]) { + var err = new Error('Missing ' + name + ' option to create user'); + done(err); + return Q.reject(err); + } + } + + var data = { + profile: { + id: options.id, + firstName: options.firstName, + lastName: options.lastName + }, + credentials: { + password: options.password + } + }; + + if (options.email) { + data.profile.email = options.email; + } + + return this.http.post(this.path + '/create', { + data: data, + done: done + }); +}; + +/** + * List users + * @param {Object} [options] + * @param {String} [options.id] Filter by the id of the user. + * @param {String} [options.firstName] Filter by the firstname of the user. + * @param {String} [options.firstNameLike] Filter by the firstname that the parameter is a substring of. + * @param {String} [options.lastName] Filter by the lastname of the user. + * @param {String} [options.lastNameLike] Filter by the lastname that the parameter is a substring of. + * @param {String} [options.email] Filter by the email of the user. + * @param {String} [options.emailLike] Filter by the email that the parameter is a substring of. + * @param {String} [options.memberOfGroup] Filter for users which are members of a group. + * @param {String} [options.sortBy] Sort the results lexicographically by a given criterion. Valid values are userId, firstName, lastName and email. Must be used in conjunction with the sortOrder parameter. + * @param {String} [options.sortOrder] Sort the results in a given order. Values may be asc for ascending order or desc for descending order. Must be used in conjunction with the sortBy parameter. + * @param {String} [options.firstResult] Pagination of results. Specifies the index of the first result to return. + * @param {String} [options.maxResults] Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. + * @param {Function} done + */ +User.list = function(options, done) { + if (typeof options === 'function') { + done = options; + options = {}; + } else { + options = options || {}; + } + return this.http.get(this.path, { + data: options, + done: done || noop + }); +}; + +/** + * Count the amount of users + * @param {String} [options.id] id of the user. + * @param {String} [options.firstName] firstname of the user. + * @param {String} [options.firstNameLike] firstname that the parameter is a substring of. + * @param {String} [options.lastName] lastname of the user. + * @param {String} [options.lastNameLike] lastname that the parameter is a substring of. + * @param {String} [options.email] email of the user. + * @param {String} [options.emailLike] email that the parameter is a substring of. + * @param {String} [options.memberOfGroup] users which are members of a group. + * @param {Function} done + */ +User.count = function(options, done) { + if (typeof options === 'function') { + done = options; + options = {}; + } else { + options = options || {}; + } + + return this.http.get(this.path + '/count', { + data: options, + done: done || noop + }); +}; + +/** + * Get the profile of a user + * @param {Object|uuid} options + * @param {uuid} options.id + * @param {Function} done + */ +User.profile = function(options, done) { + var id = typeof options === 'string' ? options : options.id; + + return this.http.get(this.path + '/' + utils.escapeUrl(id) + '/profile', { + done: done || noop + }); +}; + +/** + * Updates the profile of a user + * @param {Object} options + * @param {uuid} options.id id of the user to be updated + * @param {String} [options.firstName] + * @param {String} [options.lastName] + * @param {String} [options.email] + * @param {Function} done + */ +User.updateProfile = function(options, done) { + options = options || {}; + done = done || noop; + + if (!options.id) { + var err = new Error('Missing id option to update user profile'); + done(err); + return Q.reject(err); + } + + return this.http.put( + this.path + '/' + utils.escapeUrl(options.id) + '/profile', + { + data: options, + done: done + } + ); +}; + +/** + * Update the credentials of a user + * @param {Object} options + * @param {uuid} options.id The user's (who will be updated) id + * @param {String} options.password The user's new password. + * @param {String} [options.authenticatedUserPassword] The password of the authenticated user who changes the password of the user (ie. the user with passed id as path parameter). + * @param {Function} done + */ +User.updateCredentials = function(options, done) { + options = options || {}; + done = done || noop; + var err; + + if (!options.id) { + err = new Error('Missing id option to update user credentials'); + done(err); + return Q.reject(err); + } + + if (!options.password) { + err = new Error('Missing password option to update user credentials'); + done(err); + return Q.reject(err); + } + + var data = { + password: options.password + }; + + if (options.authenticatedUserPassword) { + data.authenticatedUserPassword = options.authenticatedUserPassword; + } + + return this.http.put( + this.path + '/' + utils.escapeUrl(options.id) + '/credentials', + { + data: data, + done: done + } + ); +}; + +/** + * Delete a user + * @param {Object|uuid} options You can either pass an object (with at least a id property) or the id of the user to be deleted + * @param {uuid} options.id + * @param {Function} done + */ +User.delete = function(options, done) { + var id = typeof options === 'string' ? options : options.id; + + return this.http.del(this.path + '/' + utils.escapeUrl(id), { + done: done || noop + }); +}; + +/** + * Unlock a user + * @param {Object|uuid} options You can either pass an object (with at least a id property) or the id of the user to be unlocked + * @param {uuid} options.id + * @param {Function} done + */ +User.unlock = function(options, done) { + var id = typeof options === 'string' ? options : options.id; + + return this.http.post(this.path + '/' + utils.escapeUrl(id) + '/unlock', { + done: done || noop + }); +}; + +module.exports = User; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/variable.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/variable.js new file mode 100644 index 0000000000000000000000000000000000000000..6b9aa088df1fd1972b465edddfc970ef24ad95ab --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/api-client/resources/variable.js @@ -0,0 +1,178 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var AbstractClientResource = require('./../abstract-client-resource'); + +/** + * Variable Resource + * @class + * @memberof CamSDK.client.resource + * @augments CamSDK.client.AbstractClientResource + */ +var Variable = AbstractClientResource.extend(); + +/** + * Path used by the resource to perform HTTP queries + * @type {String} + */ +Variable.path = 'variable-instance'; + +/** + * Get variable instances + * + * @param {Object} params + * + * @param {String} [params.variableName] Filter by variable instance name. + * + * @param {String} [params.variableNameLike] Filter by the variable instance name. + * The parameter can include the wildcard % + * to express like-strategy such as: + * - starts with (%name) + * - ends with (name%) + * - contains (%name%). + * + * @param {String[]} [params.processInstanceIdIn] Only include variable instances which + * belong to one of the passed and + * comma-separated process instance ids. + * + * @param {String[]} [params.executionIdIn] Only include variable instances which + * belong to one of the passed and + * comma-separated execution ids. + * + * @param {String[]} [params.caseInstanceIdIn] Only include variable instances which + * belong to one of the passed + * case instance ids. + * + * @param {String[]} [params.caseExecutionIdIn] Only include variable instances which + * belong to one of the passed + * case execution ids. + * + * @param {String[]} [params.taskIdIn] Only include variable instances which + * belong to one of the passed and + * comma-separated task ids. + * + * @param {String[]} [params.activityInstanceIdIn] Only include variable instances which + * belong to one of the passed and + * comma-separated activity instance ids. + * + * @param {String} [params.variableValues] Only include variable instances that + * have the certain values. Value filtering + * expressions are comma-separated and are + * structured as follows: + * A valid parameter value has the form + * key_operator_value. + * key is the variable name, + * operator is the comparison operator to + * be used and value the variable value. + * *Note*: Values are always treated as + * String objects on server side. + * Valid operator values are: + * - eq - equal to + * - neq - not equal to + * - gt - greater than + * - gteq - greater than or equal to + * - lt - lower than + * - lteq - lower than or equal to + * key and value may not contain underscore + * or comma characters. + * + * @param {String} [params.sortBy] Sort the results lexicographically by a + * given criterion. Valid values are + * variableName, variableType and + * activityInstanceId. + * Must be used in conjunction with the + * sortOrder parameter. + * + * @param {String} [params.sortOrder] Sort the results in a given order. + * Values may be asc for ascending order or + * desc for descending order. + * Must be used in conjunction with the + * sortBy parameter. + * + * @param {String} [params.firstResult] Pagination of results. Specifies the + * index of the first result to return. + * + * @param {String} [params.maxResults] Pagination of results. Specifies the + * maximum number of results to return. + * Will return less results if there are no + * more results left. + * + * @param {String} [params.deserializeValues] Determines whether serializable variable + * values (typically variables that store + * custom Java objects) should be + * deserialized on server side + * (default true). + * If set to true, a serializable variable + * will be deserialized on server side and + * transformed to JSON using + * Jackson's POJO/bean property + * introspection feature. + * Note that this requires the Java classes + * of the variable value to be on the + * REST API's classpath. + * If set to false, a serializable variable + * will be returned in its serialized + * format. + * For example, a variable that is + * serialized as XML will be returned as a + * JSON string containing XML. + * Note:While true is the default value for + * reasons of backward compatibility, we + * recommend setting this parameter to + * false when developing web applications + * that are independent of the Java process + * applications deployed to the engine. + * + * @param {RequestCallback} done + */ +Variable.instances = function(params, done) { + var body = {}; + var query = {}; + var queryParams = ['firstResult', 'maxResults', 'deserializeValues']; + + for (var p in params) { + if (queryParams.indexOf(p) > -1) { + query[p] = params[p]; + } else { + body[p] = params[p]; + } + } + + return this.http.post(this.path, { + data: body, + query: query, + done: done + }); +}; + +/** + * Get a count of variables + * Same parameters as instances + */ + +Variable.count = function(params, done) { + var path = this.path + '/count'; + + return this.http.post(path, { + data: params, + done: done + }); +}; + +module.exports = Variable; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/base-class.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/base-class.js new file mode 100644 index 0000000000000000000000000000000000000000..1c34e0ba87e54fc7872175d93d4bc356cc97fe69 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/base-class.js @@ -0,0 +1,98 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var Events = require('./events'); + +function noop() {} + +/** + * Abstract class for classes + * + * @class + * @memberof CamSDK + * + * @borrows CamSDK.Events.on as on + * @borrows CamSDK.Events.once as once + * @borrows CamSDK.Events.off as off + * @borrows CamSDK.Events.trigger as trigger + * + * @borrows CamSDK.Events.on as prototype.on + * @borrows CamSDK.Events.once as prototype.once + * @borrows CamSDK.Events.off as prototype.off + * @borrows CamSDK.Events.trigger as prototype.trigger + */ +function BaseClass() { + this.initialize(); +} + +/** + * Creates a new Resource Class, very much inspired from Backbone.Model.extend. + * [Backbone helpers]{@link http://backbonejs.org/docs/backbone.html} + * + * + * @param {?Object.} protoProps + * @param {Object.} [staticProps] + * @return {CamSDK.BaseClass} + */ +BaseClass.extend = function(protoProps, staticProps) { + protoProps = protoProps || {}; + staticProps = staticProps || {}; + + var parent = this; + var child, Surrogate, s, i; + + if (protoProps && Object.hasOwnProperty.call(parent, 'constructor')) { + child = protoProps.constructor; + } else { + child = function() { + return parent.apply(this, arguments); + }; + } + + for (s in parent) { + child[s] = parent[s]; + } + for (s in staticProps) { + child[s] = staticProps[s]; + } + + Surrogate = function() { + this.constructor = child; + }; + Surrogate.prototype = parent.prototype; + child.prototype = new Surrogate(); + + for (i in protoProps) { + child.prototype[i] = protoProps[i]; + } + + return child; +}; + +/** + * Aimed to be overriden in order to initialize an instance. + * + * @memberof CamSDK.BaseClass.prototype + * @method initialize + */ +BaseClass.prototype.initialize = noop; + +Events.attach(BaseClass); + +module.exports = BaseClass; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/events.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/events.js new file mode 100644 index 0000000000000000000000000000000000000000..987c99d95b014388d5ae74671dca4998b36cdb5e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/events.js @@ -0,0 +1,164 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +/** + * Events handling utility which can be used on + * any kind of object to provide `on`, `once`, `off` + * and `trigger` functions. + * + * @exports CamSDK.Events + * @mixin + * + * @example + * var obj = {}; + * Events.attach(obj); + * + * obj.on('event:name', function() {}); + * obj.once('event:name', function() {}); + * obj.trigger('event:name', data, moreData, evenMoreData); + */ + +var Events = {}; + +/** + * Converts an object into array + * @param {*} obj + * @return {Array} + */ +function toArray(obj) { + var a, + arr = []; + for (a in obj) { + arr.push(obj[a]); + } + return arr; +} + +/** + * Returns a function that will be executed + * at most one time, no matter how often you call it. + * @param {Function} func + * @return {Function} + */ +function once(func) { + var ran = false, + memo; + return function() { + if (ran) return memo; + ran = true; + memo = func.apply(this, arguments); + func = null; + return memo; + }; +} + +/** + * Ensure an object to have the needed _events property + * @param {*} obj + * @param {String} name + */ +function ensureEvents(obj, name) { + obj._events = obj._events || {}; + obj._events[name] = obj._events[name] || []; +} + +/** + * Add the relevant Events methods to an object + * @param {*} obj + */ +Events.attach = function(obj) { + obj.on = this.on; + obj.once = this.once; + obj.off = this.off; + obj.trigger = this.trigger; + obj._events = {}; +}; + +/** + * Bind a callback to `eventName` + * @param {String} eventName + * @param {Function} callback + */ +Events.on = function(eventName, callback) { + ensureEvents(this, eventName); + + this._events[eventName].push(callback); + + return this; +}; + +/** + * Bind a callback who will only be called once to `eventName` + * @param {String} eventName + * @param {Function} callback + */ +Events.once = function(eventName, callback) { + var self = this; + var cb = once(function() { + self.off(eventName, once); + callback.apply(this, arguments); + }); + cb._callback = callback; + return this.on(eventName, cb); +}; + +/** + * Unbind one or all callbacks originally bound to `eventName` + * @param {String} eventName + * @param {Function} [callback] + */ +Events.off = function(eventName, callback) { + ensureEvents(this, eventName); + + if (!callback) { + delete this._events[eventName]; + return this; + } + + var e, + arr = []; + for (e in this._events[eventName]) { + if (this._events[eventName][e] !== callback) { + arr.push(this._events[eventName][e]); + } + } + this._events[eventName] = arr; + + return this; +}; + +/** + * Call the functions bound to `eventName` + * @param {String} eventName + * @param {...*} [params] + */ +Events.trigger = function() { + var args = toArray(arguments); + var eventName = args.shift(); + ensureEvents(this, eventName); + + var e; + for (e in this._events[eventName]) { + this._events[eventName][e](this, args); + } + + return this; +}; + +module.exports = Events; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/forms/camunda-form.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/forms/camunda-form.js new file mode 100644 index 0000000000000000000000000000000000000000..63441f28cecc3b37b9a0abf24f535e3cac66dad2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/forms/camunda-form.js @@ -0,0 +1,870 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; +/* global CamSDK */ + +/** + * For all API client related + * @namespace CamSDK.form + */ + +var moment = require('moment'); + +var $ = require('./dom-lib'); + +var VariableManager = require('./variable-manager'); + +var InputFieldHandler = require('./controls/input-field-handler'); + +var ChoicesFieldHandler = require('./controls/choices-field-handler'); + +var FileDownloadHandler = require('./controls/file-download-handler'); + +var ErrorButtonHandler = require('./controls/error-button-handler'); + +var EscalationButtonHandler = require('./controls/escalation-button-handler'); + +var BaseClass = require('./../base-class'); + +var constants = require('./constants'); + +var Events = require('./../events'); + +function extend(dest, add) { + for (var key in add) { + dest[key] = add[key]; + } + return dest; +} + +/** + * A class to help handling embedded forms + * + * @class + * @memberof CamSDk.form + * + * @param {Object.} options + * @param {Cam} options.client + * @param {String} [options.taskId] + * @param {String} [options.processDefinitionId] + * @param {String} [options.processDefinitionKey] + * @param {Element} [options.formContainer] + * @param {Element} [options.formElement] + * @param {Object} [options.urlParams] + * @param {String} [options.formUrl] + */ +function CamundaForm(options) { + if (!options) { + throw new Error('CamundaForm need to be initialized with options.'); + } + + var done = (options.done = + options.done || + function(err) { + if (err) throw err; + }); + + if (options.client) { + this.client = options.client; + } else { + this.client = new CamSDK.Client(options.clientConfig || {}); + } + + if ( + !options.taskId && + !options.processDefinitionId && + !options.processDefinitionKey + ) { + return done( + new Error( + "Cannot initialize Taskform: either 'taskId' or 'processDefinitionId' or 'processDefinitionKey' must be provided" + ) + ); + } + + this.taskId = options.taskId; + if (this.taskId) { + this.taskBasePath = this.client.baseUrl + '/task/' + this.taskId; + } + this.processDefinitionId = options.processDefinitionId; + this.processDefinitionKey = options.processDefinitionKey; + + this.formElement = options.formElement; + this.containerElement = options.containerElement; + this.formUrl = options.formUrl; + + if (!this.formElement && !this.containerElement) { + return done( + new Error( + "CamundaForm needs to be initilized with either 'formElement' or 'containerElement'" + ) + ); + } + + if (!this.formElement && !this.formUrl) { + return done( + new Error( + "Camunda form needs to be intialized with either 'formElement' or 'formUrl'" + ) + ); + } + + /** + * A VariableManager instance + * @type {VariableManager} + */ + this.variableManager = new VariableManager({ + client: this.client + }); + + /** + * An array of FormFieldHandlers + * @type {FormFieldHandlers[]} + */ + this.formFieldHandlers = options.formFieldHandlers || [ + InputFieldHandler, + ChoicesFieldHandler, + FileDownloadHandler, + ErrorButtonHandler, + EscalationButtonHandler + ]; + + this.businessKey = null; + + this.fields = []; + + this.scripts = []; + + this.options = options; + + // init event support + Events.attach(this); + + this.initialize(done); +} + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.initializeHandler = function(FieldHandler) { + var self = this; + var selector = FieldHandler.selector; + + $(selector, self.formElement).each(function() { + self.fields.push(new FieldHandler(this, self.variableManager, self)); + }); +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.initialize = function(done) { + done = + done || + function(err) { + if (err) throw err; + }; + var self = this; + + // check whether form needs to be loaded first + if (this.formUrl) { + this.client.http.load(this.formUrl, { + accept: '*/*', + done: function(err, result) { + if (err) { + return done(err); + } + + try { + self.renderForm(result); + self.initializeForm(done); + } catch (error) { + done(error); + } + }, + data: extend({noCache: Date.now()}, this.options.urlParams || {}) + }); + } else { + try { + this.initializeForm(done); + } catch (error) { + done(error); + } + } +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.renderForm = function(formHtmlSource) { + // apppend the form html to the container element, + // we also wrap the formHtmlSource to limit the risks of breaking + // the structure of the document + $(this.containerElement) + .html('') + .append('
' + formHtmlSource + '
'); + + // extract and validate form element + var formElement = (this.formElement = $('form', this.containerElement)); + if (formElement.length !== 1) { + throw new Error('Form must provide exactly one element
'); + } + if (!formElement.attr('name')) { + formElement.attr('name', '$$camForm'); + } +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.initializeForm = function(done) { + var self = this; + + // handle form scripts + this.initializeFormScripts(); + + // initialize field handlers + this.initializeFieldHandlers(); + + // execute the scripts + this.executeFormScripts(); + + // fire form loaded + this.fireEvent('form-loaded'); + + this.fetchVariables(function(err, result) { + if (err) { + throw err; + } + + // merge the variables + self.mergeVariables(result); + + // retain original server values for dirty checking + self.storeOriginalValues(result); + + // fire variables fetched + self.fireEvent('variables-fetched'); + + // restore variables from local storage + self.restore(); + + // fire variables-restored + self.fireEvent('variables-restored'); + + // apply the variables to the form fields + self.applyVariables(); + + // fire variables applied + self.fireEvent('variables-applied'); + + // invoke callback + done(null, self); + }); +}; + +CamundaForm.prototype.initializeFieldHandlers = function() { + for (var FieldHandler in this.formFieldHandlers) { + this.initializeHandler(this.formFieldHandlers[FieldHandler]); + } +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.initializeFormScripts = function() { + var formScriptElements = $( + 'script[' + constants.DIRECTIVE_CAM_SCRIPT + ']', + this.formElement + ); + for (var i = 0; i < formScriptElements.length; i++) { + this.scripts.push(formScriptElements[i].text); + } +}; + +CamundaForm.prototype.executeFormScripts = function() { + for (var i = 0; i < this.scripts.length; i++) { + this.executeFormScript(this.scripts[i]); + } +}; + +CamundaForm.prototype.executeFormScript = function(script) { + /*eslint-disable */ + /* jshint unused: false */ + (function(camForm) { + + /* jshint evil: true */ + eval(script); + /* jshint evil: false */ + + })(this); + /*eslint-enable */ +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + * + * Store the state of the form to localStorage. + * + * You can prevent further execution by hooking + * the `store` event and set `storePrevented` to + * something truthy. + */ +CamundaForm.prototype.store = function(callback) { + var formId = this.taskId || this.processDefinitionId || this.caseInstanceId; + + if (!formId) { + if (typeof callback === 'function') { + return callback(new Error('Cannot determine the storage ID')); + } else { + throw new Error('Cannot determine the storage ID'); + } + } + + this.storePrevented = false; + this.fireEvent('store'); + if (this.storePrevented) { + return; + } + + try { + // get values from form fields + this.retrieveVariables(); + + // build the local storage object + var store = {date: Date.now(), vars: {}}; + for (var name in this.variableManager.variables) { + if ( + !['Bytes', 'File'].includes(this.variableManager.variables[name].type) + ) { + store.vars[name] = this.variableManager.variables[name].value; + } + } + + // store it + localStorage.setItem('camForm:' + formId, JSON.stringify(store)); + } catch (error) { + if (typeof callback === 'function') { + return callback(error); + } else { + throw error; + } + } + this.fireEvent('variables-stored'); + if (typeof callback === 'function') { + callback(); + } +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + * @return {Boolean} `true` if there is something who can be restored + */ +CamundaForm.prototype.isRestorable = function() { + var formId = this.taskId || this.processDefinitionId || this.caseInstanceId; + + if (!formId) { + throw new Error('Cannot determine the storage ID'); + } + + // verify the presence of an entry + if (!localStorage.getItem('camForm:' + formId)) { + return false; + } + + // unserialize + var stored = localStorage.getItem('camForm:' + formId); + try { + stored = JSON.parse(stored); + } catch (error) { + return false; + } + + // check the content + if (!stored || !Object.keys(stored).length) { + return false; + } + + return true; +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + * + * Restore the state of the form from localStorage. + * + * You can prevent further execution by hooking + * the `restore` event and set `restorePrevented` to + * something truthy. + */ +CamundaForm.prototype.restore = function(callback) { + var stored; + var vars = this.variableManager.variables; + var formId = this.taskId || this.processDefinitionId || this.caseDefinitionId; + + if (!formId) { + if (typeof callback === 'function') { + return callback(new Error('Cannot determine the storage ID')); + } else { + throw new Error('Cannot determine the storage ID'); + } + } + + // no need to go further if there is nothing to restore + if (!this.isRestorable()) { + if (typeof callback === 'function') { + return callback(); + } + return; + } + + try { + // retrieve the values from localStoarge + stored = localStorage.getItem('camForm:' + formId); + stored = JSON.parse(stored).vars; + } catch (error) { + if (typeof callback === 'function') { + return callback(error); + } else { + throw error; + } + } + + // merge the stored values on the variableManager.variables + for (var name in stored) { + if (vars[name]) { + vars[name].value = stored[name]; + } else { + vars[name] = { + name: name, + value: stored[name] + }; + } + } + + if (typeof callback === 'function') { + callback(); + } +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.submit = function(callback) { + var formId = this.taskId || this.processDefinitionId; + + // fire submit event (event handler may prevent submit from being performed) + this.submitPrevented = false; + this.fireEvent('submit'); + if (this.submitPrevented) { + var err = new Error('camForm submission prevented'); + this.fireEvent('submit-failed', err); + return callback && callback(err); + } + + try { + // get values from form fields + this.retrieveVariables(); + } catch (error) { + return callback && callback(error); + } + + var self = this; + this.transformFiles(function() { + // submit the form variables + self.submitVariables(function(err, result) { + if (err) { + self.fireEvent('submit-failed', err); + return callback && callback(err); + } + + // clear the local storage for this form + localStorage.removeItem('camForm:' + formId); + + self.fireEvent('submit-success'); + return callback && callback(null, result); + }); + }); +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.error = function(errorCode, errorMessage, callback) { + var formId = this.taskId || this.processDefinitionId; + + this.errorPrevented = false; + this.fireEvent('error'); + if (this.errorPrevented) { + var err = new Error('camForm error prevented'); + this.fireEvent('error-failed', err); + return callback && callback(err); + } + + try { + // get values from form fields + this.retrieveVariables(); + } catch (error) { + return callback && callback(error); + } + + var self = this; + this.transformFiles(function() { + // submit the form variables + var data = { + variables: self.parseVariables(), + id: self.taskId, + errorCode: errorCode, + errorMessage: errorMessage + }; + self.client.resource('task').bpmnError(data, function(err, result) { + if (err) { + self.fireEvent('error-failed', err); + return callback && callback(err); + } + + // clear the local storage for this form + localStorage.removeItem('camForm:' + formId); + + self.fireEvent('error-success'); + return callback && callback(null, result); + }); + }); +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.escalate = function(escalationCode, callback) { + var formId = this.taskId || this.processDefinitionId; + + this.escalationPrevented = false; + this.fireEvent('escalation'); + if (this.escalationPrevented) { + var err = new Error('camForm escalation prevented'); + this.fireEvent('escalation-failed', err); + return callback && callback(err); + } + + try { + // get values from form fields + this.retrieveVariables(); + } catch (error) { + return callback && callback(error); + } + + var self = this; + this.transformFiles(function() { + // submit the form variables + var data = { + variables: self.parseVariables(), + id: self.taskId, + escalationCode: escalationCode + }; + self.client.resource('task').bpmnEscalation(data, function(err, result) { + if (err) { + self.fireEvent('escalation-failed', err); + return callback && callback(err); + } + + // clear the local storage for this form + localStorage.removeItem('camForm:' + formId); + + self.fireEvent('escalation-success'); + return callback && callback(null, result); + }); + }); +}; + +CamundaForm.prototype.transformFiles = function(callback) { + var that = this; + var counter = 1; + + var callCallback = function() { + if (--counter === 0) { + callback(); + } + }; + + var bytesToSize = function(bytes) { + if (bytes === 0) return '0 Byte'; + var k = 1000; + var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + var i = Math.floor(Math.log(bytes) / Math.log(k)); + return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]; + }; + + for (var i in this.fields) { + var element = this.fields[i].element[0]; + if (element.getAttribute('type') === 'file') { + var fileVar = that.variableManager.variables[that.fields[i].variableName]; + + if (typeof FileReader === 'function' && element.files.length > 0) { + if ( + element.files[0].size > + (parseInt(element.getAttribute('cam-max-filesize'), 10) || 5000000) + ) { + throw new Error( + 'Maximum file size of ' + + bytesToSize( + parseInt(element.getAttribute('cam-max-filesize'), 10) || + 5000000 + ) + + ' exceeded.' + ); + } + var reader = new FileReader(); + /* jshint ignore:start */ + reader.onloadend = (function(i, element, fileVar) { + return function(e) { + var binary = ''; + var bytes = new Uint8Array(e.target.result); + var len = bytes.byteLength; + for (var j = 0; j < len; j++) { + binary += String.fromCharCode(bytes[j]); + } + + fileVar.value = btoa(binary); + + // set file metadata as value info + if (fileVar.type.toLowerCase() === 'file') { + fileVar.valueInfo = { + filename: element.files[0].name, + mimeType: element.files[0].type + }; + } + + callCallback(); + }; + })(i, element, fileVar); + /* jshint ignore:end */ + reader.readAsArrayBuffer(element.files[0]); + counter++; + } else { + fileVar.value = ''; + fileVar.valueInfo = { + filename: '' + }; + } + } + } + + callCallback(); +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.fetchVariables = function(done) { + done = done || function() {}; + var names = this.variableManager.variableNames(); + if (names.length) { + var data = { + names: names, + deserializeValues: false + }; + + // pass either the taskId, processDefinitionId or processDefinitionKey + if (this.taskId) { + data.id = this.taskId; + this.client.resource('task').formVariables(data, done); + } else { + data.id = this.processDefinitionId; + data.key = this.processDefinitionKey; + this.client.resource('process-definition').formVariables(data, done); + } + } else { + done(); + } +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.parseVariables = function() { + var varManager = this.variableManager; + var vars = varManager.variables; + + // The default display value is different from the original value in varManager + this.fields.forEach(function(field) { + if (vars[field.variableName]) { + vars[field.variableName].defaultValue = field.originalValue; + + if ( + field.originalValue === '' || + typeof field.originalValue === 'undefined' + ) { + vars[field.variableName].defaultValue = vars[field.variableName].value; + } + } + }); + + var variableData = {}; + for (var v in vars) { + // only submit dirty variables + // LIMITATION: dirty checking is not performed for complex object variables + + var val = vars[v].value; + + // We want implicit type conversion in this case, the defaultValue is always a string + if (varManager.isDirty(v) || vars[v].defaultValue != val) { + // if variable is JSON, serialize + + if (varManager.isJsonVariable(v)) { + val = JSON.stringify(val); + } + + // if variable is Date, add timezone info + if (val && varManager.isDateVariable(v)) { + val = moment(val, moment.ISO_8601).format('YYYY-MM-DDTHH:mm:ss.SSSZZ'); + } + + variableData[v] = { + value: val, + type: vars[v].type, + valueInfo: vars[v].valueInfo + }; + } + } + return variableData; +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.submitVariables = function(done) { + done = done || function() {}; + + var data = {variables: this.parseVariables()}; + + // pass either the taskId, processDefinitionId or processDefinitionKey + if (this.taskId) { + data.id = this.taskId; + this.client.resource('task').submitForm(data, done); + } else { + var businessKey = + this.businessKey || + this.formElement.find('input[type="text"][cam-business-key]').val(); + if (businessKey) { + data.businessKey = businessKey; + } + data.id = this.processDefinitionId; + data.key = this.processDefinitionKey; + this.client.resource('process-definition').submitForm(data, done); + } +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.storeOriginalValues = function(variables) { + for (var v in variables) { + this.variableManager.setOriginalValue(v, variables[v].value); + } +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.mergeVariables = function(variables) { + var vars = this.variableManager.variables; + + for (var v in variables) { + if (vars[v]) { + for (var p in variables[v]) { + vars[v][p] = vars[v][p] || variables[v][p]; + } + } else { + vars[v] = variables[v]; + } + // check whether the variable provides JSON payload. If true, deserialize + if (this.variableManager.isJsonVariable(v)) { + vars[v].value = JSON.parse(variables[v].value); + } + + // generate content url for file and bytes variables + var type = vars[v].type; + if (!!this.taskBasePath && (type === 'Bytes' || type === 'File')) { + vars[v].contentUrl = + this.taskBasePath + '/variables/' + vars[v].name + '/data'; + } + + this.variableManager.isVariablesFetched = true; + } +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.applyVariables = function() { + for (var i in this.fields) { + this.fields[i].applyValue(); + } +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.retrieveVariables = function() { + for (var i in this.fields) { + this.fields[i].getValue(); + } +}; + +/** + * @memberof CamSDK.form.CamundaForm.prototype + */ +CamundaForm.prototype.fireEvent = function(eventName, obj) { + this.trigger(eventName, obj); +}; + +/** + * @memberof CamSDK.form.CamundaForm + */ +CamundaForm.$ = $; + +CamundaForm.VariableManager = VariableManager; +CamundaForm.fields = {}; +CamundaForm.fields.InputFieldHandler = InputFieldHandler; +CamundaForm.fields.ChoicesFieldHandler = ChoicesFieldHandler; + +/** + * @memberof CamSDK.form.CamundaForm + */ +CamundaForm.cleanLocalStorage = function(timestamp) { + for (var i = 0; i < localStorage.length; i++) { + var key = localStorage.key(i); + if (key.indexOf('camForm:') === 0) { + var item = JSON.parse(localStorage.getItem(key)); + if (item.date < timestamp) { + localStorage.removeItem(key); + i--; + } + } + } +}; + +/** + * @memberof CamSDK.form.CamundaForm + * @borrows CamSDK.BaseClass.extend as extend + * @name extend + * @type {Function} + */ +CamundaForm.extend = BaseClass.extend; + +module.exports = CamundaForm; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/forms/constants.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/forms/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..6294538c47e84d2243432ce451a7dd954475c287 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/forms/constants.js @@ -0,0 +1,30 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +module.exports = { + DIRECTIVE_CAM_FORM: 'cam-form', + DIRECTIVE_CAM_VARIABLE_NAME: 'cam-variable-name', + DIRECTIVE_CAM_VARIABLE_TYPE: 'cam-variable-type', + DIRECTIVE_CAM_FILE_DOWNLOAD: 'cam-file-download', + DIRECTIVE_CAM_CHOICES: 'cam-choices', + DIRECTIVE_CAM_SCRIPT: 'cam-script', + DIRECTIVE_CAM_ERROR_CODE: 'cam-error-code', + DIRECTIVE_CAM_ERROR_MESSAGE: 'cam-error-message', + DIRECTIVE_CAM_ESCALATION_CODE: 'cam-escalation-code' +}; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/forms/controls/abstract-form-field.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/forms/controls/abstract-form-field.js new file mode 100644 index 0000000000000000000000000000000000000000..155427a8b4309e8020f3e26e8f9a908888422c29 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/forms/controls/abstract-form-field.js @@ -0,0 +1,84 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var BaseClass = require('../../base-class'); +var $ = require('./../dom-lib'); + +function noop() {} + +/** + * An abstract class for the form field controls + * + * @class AbstractFormField + * @abstract + * @memberof CamSDK.form + * + */ +function AbstractFormField(element, variableManager, camForm) { + this.element = $(element); + this.variableManager = variableManager; + this.form = camForm; + + this.variableName = null; + + this.initialize(); +} + +/** + * @memberof CamSDK.form.AbstractFormField + * @abstract + * @name selector + * @type {String} + */ +AbstractFormField.selector = null; + +/** + * @memberof CamSDK.form.AbstractFormField + * @borrows CamSDK.BaseClass.extend as extend + * @name extend + * @type {Function} + */ +AbstractFormField.extend = BaseClass.extend; + +/** + * @memberof CamSDK.form.AbstractFormField.prototype + * @abstract + * @method initialize + */ +AbstractFormField.prototype.initialize = noop; + +/** + * Applies the stored value to a field element. + * + * @memberof CamSDK.form.AbstractFormField.prototype + * @abstract + * @method applyValue + * + * @return {CamSDK.form.AbstractFormField} Chainable method + */ +AbstractFormField.prototype.applyValue = noop; + +/** + * @memberof CamSDK.form.AbstractFormField.prototype + * @abstract + * @method getValue + */ +AbstractFormField.prototype.getValue = noop; + +module.exports = AbstractFormField; diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/forms/controls/choices-field-handler.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/forms/controls/choices-field-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..87c13168a60d533e7f7109967a278803e2d62648 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/webapps/frontend/camunda-bpm-sdk-js/lib/forms/controls/choices-field-handler.js @@ -0,0 +1,164 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +var constants = require('./../constants'), + AbstractFormField = require('./abstract-form-field'), + $ = require('./../dom-lib'); + +/** + * A field control handler for choices + * @class + * @memberof CamSDK.form + * @augments {CamSDK.form.AbstractFormField} + */ +var ChoicesFieldHandler = AbstractFormField.extend( + /** @lends CamSDK.form.ChoicesFieldHandler.prototype */ + { + /** + * Prepares an instance + */ + initialize: function() { + // read variable definitions from markup + var variableName = (this.variableName = this.element.attr( + constants.DIRECTIVE_CAM_VARIABLE_NAME + )); + var variableType = (this.variableType = this.element.attr( + constants.DIRECTIVE_CAM_VARIABLE_TYPE + )); + var choicesVariableName = (this.choicesVariableName = this.element.attr( + constants.DIRECTIVE_CAM_CHOICES + )); + + // crate variable + this.variableManager.createVariable({ + name: variableName, + type: variableType + }); + + // fetch choices variable + if (choicesVariableName) { + this.variableManager.fetchVariable(choicesVariableName); + } + + this.previousValue = this.originalValue = ''; + + // remember variable name + this.variableName = variableName; + }, + + /** + * Applies the stored value to a field element. + * + * @return {CamSDK.form.ChoicesFieldHandler} Chainable method. + */ + applyValue: function() { + var selectedIndex = this.element[0].selectedIndex; + // if cam-choices variable is defined, apply options + if (this.choicesVariableName) { + var choicesVariableValue = this.variableManager.variableValue( + this.choicesVariableName + ); + if (choicesVariableValue) { + // array + if (choicesVariableValue instanceof Array) { + for (var i = 0; i < choicesVariableValue.length; i++) { + var val = choicesVariableValue[i]; + if (!this.element.find('option[text="' + val + '"]').length) { + this.element.append( + $('