From 99956f1cc41f17ff32df8cba9d7ce533801e0963 Mon Sep 17 00:00:00 2001 From: Lukas Krecan Date: Wed, 1 Nov 2023 17:25:26 +0100 Subject: [PATCH 1/2] Add Spotless linter --- .github/workflows/build.yml | 2 +- .../shedlock/cdi/SchedulerLock.java | 41 ++--- .../CdiLockConfigurationExtractor.java | 47 ++---- .../LockingNotSupportedException.java | 14 +- .../internal/SchedulerLockInterceptor.java | 29 ++-- .../shedlock/cdi/SchedulerLock.java | 38 +++-- .../CdiLockConfigurationExtractor.java | 47 ++---- .../LockingNotSupportedException.java | 14 +- .../internal/SchedulerLockInterceptor.java | 19 +-- .../src/main/java/QuarkusProdConfig.java | 5 +- .../shedlock/quarkus/test/QuarkusConfig.java | 32 ++-- .../quarkus/test/QuarkusShedlockTest.java | 40 +++-- .../shedlock/quarkus/test/TestUtils.java | 28 ++-- .../shedlock/micronaut/SchedulerLock.java | 47 +++--- .../LockingNotSupportedException.java | 14 +- .../MicronautLockConfigurationExtractor.java | 56 +++---- .../internal/SchedulerLockInterceptor.java | 41 ++--- .../internal/MethodProxyAopConfig.java | 32 ++-- .../internal/MethodProxyAopTest.java | 36 ++--- .../micronaut/internal/TestUtils.java | 28 ++-- .../shedlock/micronaut/SchedulerLock.java | 47 +++--- .../LockingNotSupportedException.java | 14 +- .../MicronautLockConfigurationExtractor.java | 56 +++---- .../internal/SchedulerLockInterceptor.java | 51 +++---- .../internal/MethodProxyAopConfig.java | 32 ++-- .../internal/MethodProxyAopTest.java | 36 ++--- .../micronaut/internal/TestUtils.java | 28 ++-- .../micronaut/test/Application.java | 16 +- .../micronaut/test/Configuration.java | 17 +-- .../micronaut/test/ScheduledTasks.java | 21 ++- .../micronaut/test/ApplicationTest.java | 20 ++- .../micronaut/test/Application.java | 16 +- .../micronaut/test/Configuration.java | 17 +-- .../micronaut/test/ScheduledTasks.java | 21 ++- .../micronaut/test/ApplicationTest.java | 20 ++- .../micronaut/test/Application.java | 16 +- .../micronaut/test/Configuration.java | 17 +-- .../micronaut/test/ScheduledTasks.java | 21 ++- .../micronaut/test/ApplicationTest.java | 20 ++- .../micronaut/test/Application.java | 16 +- .../micronaut/test/Configuration.java | 17 +-- .../micronaut/test/ScheduledTasks.java | 21 ++- .../micronaut/test/ApplicationTest.java | 20 ++- pom.xml | 11 ++ .../provider/arangodb/ArangoLockProvider.java | 93 ++++++------ .../ArangoLockProviderIntegrationTest.java | 44 +++--- .../cassandra/CassandraLockProvider.java | 67 ++++----- .../cassandra/CassandraStorageAccessor.java | 120 ++++++++------- .../shedlock/provider/cassandra/Lock.java | 17 +-- .../CassandraLockProviderIntegrationTest.java | 56 ++++--- .../provider/consul/ConsulLockProvider.java | 136 +++++++++-------- .../provider/consul/ConsulSimpleLock.java | 19 +-- .../ConsulLockProviderIntegrationTest.java | 60 +++----- .../consul/ConsulLockProviderTest.java | 61 ++++---- .../javaclient3/CouchbaseLockProvider.java | 74 +++++---- .../CouchbaseLockProviderIntegrationTest.java | 50 +++--- .../datastore/DatastoreLockProvider.java | 7 +- .../datastore/DatastoreStorageAccessor.java | 108 +++++++------ .../DatastoreLockProviderIntegrationTest.java | 36 ++--- .../dynamodb2/DynamoDBLockProvider.java | 88 +++++------ .../provider/dynamodb2/DynamoDBUtils.java | 42 +++--- .../DynamoDBLockProviderIntegrationTest.java | 98 ++++++------ .../ElasticsearchLockProvider.java | 122 ++++++++------- .../ElasticsearchLockProviderTest.java | 76 +++++----- .../provider/etcd/jetcd/EtcdLockProvider.java | 65 ++++---- .../EtcdLockProviderIntegrationTest.java | 33 ++-- .../provider/hazelcast4/HazelcastLock.java | 46 +++--- .../hazelcast4/HazelcastLockProvider.java | 98 ++++++------ .../hazelcast4/HazelcastSimpleLock.java | 19 +-- .../HazelcastLockProviderClusterTest.java | 39 +++-- .../HazelcastLockProviderIntegrationTest.java | 23 ++- .../provider/ignite/IgniteLockProvider.java | 110 +++++++------- .../shedlock/provider/ignite/LockValue.java | 27 ++-- .../ignite/IgniteLockProviderTest.java | 27 ++-- .../inmemory/InMemoryLockProvider.java | 25 ++- .../InMemoryLockProviderIntegrationTest.java | 4 +- .../internal/AbstractJdbcStorageAccessor.java | 125 ++++++++------- .../micronaut/MicronautJdbcLockProvider.java | 61 ++++---- .../MicronautJdbcStorageAccessor.java | 29 ++-- .../HsqlJdbcLockProviderIntegrationTest.java | 14 +- .../MySqlJdbcLockProviderIntegrationTest.java | 14 +- ...stgresJdbcLockProviderIntegrationTest.java | 14 +- .../jdbctemplate/DatabaseProduct.java | 21 +-- .../Db2ServerTimeStatementsSource.java | 45 +++--- .../H2ServerTimeStatementsSource.java | 43 +++--- .../HsqlServerTimeStatementsSource.java | 43 +++--- .../JdbcTemplateLockProvider.java | 131 ++++++++-------- .../JdbcTemplateStorageAccessor.java | 32 ++-- .../MsSqlServerTimeStatementsSource.java | 46 +++--- .../MySqlServerTimeStatementsSource.java | 45 +++--- .../OracleServerTimeStatementsSource.java | 46 +++--- ...PostgresSqlServerTimeStatementsSource.java | 49 +++--- .../PostgresSqlStatementsSource.java | 21 ++- .../jdbctemplate/SqlStatementsSource.java | 65 ++++---- ...bcTemplateLockProviderIntegrationTest.java | 39 ++--- ...stractJdbcTemplateStorageAccessorTest.java | 51 +++---- ...bcTemplateLockProviderIntegrationTest.java | 14 +- ...bcTemplateLockProviderIntegrationTest.java | 14 +- ...bcTemplateLockProviderIntegrationTest.java | 55 ++++--- .../JdbcTemplateLockProviderTest.java | 53 +++---- .../JdbcTemplateStorageAccessorTest.java | 31 ++-- ...bcTemplateLockProviderIntegrationTest.java | 14 +- ...bcTemplateLockProviderIntegrationTest.java | 17 +-- ...ltiTenancyLockProviderIntegrationTest.java | 62 ++++---- ...bcTemplateLockProviderIntegrationTest.java | 15 +- ...bcTemplateLockProviderIntegrationTest.java | 14 +- ...bcTemplateLockProviderIntegrationTest.java | 70 ++++----- ...bcTemplateLockProviderIntegrationTest.java | 30 ++-- .../provider/jdbctemplate/ServerTimeTest.java | 41 ++--- .../provider/jdbc/JdbcLockProvider.java | 48 +++--- .../provider/jdbc/JdbcStorageAccessor.java | 28 ++-- .../HsqlJdbcLockProviderIntegrationTest.java | 14 +- .../MySqlJdbcLockProviderIntegrationTest.java | 14 +- ...stgresJdbcLockProviderIntegrationTest.java | 14 +- .../provider/jooq/JooqLockProvider.java | 15 +- .../provider/jooq/JooqStorageAccessor.java | 82 ++++++---- .../shedlock/provider/jooq/Shedlock.java | 79 ++++------ ...stractJooqLockProviderIntegrationTest.java | 27 ++-- .../HsqlJooqLockProviderIntegrationTest.java | 21 +-- ...ariaDbJooqLockProviderIntegrationTest.java | 14 +- .../MySqlJooqLockProviderIntegrationTest.java | 14 +- ...stgresJooqLockProviderIntegrationTest.java | 14 +- .../jdbc/AbstractContainerBasedDbConfig.java | 17 +-- .../test/support/jdbc/AbstractDbConfig.java | 23 +-- ...stractJdbcLockProviderIntegrationTest.java | 55 ++++--- .../test/support/jdbc/Db2ServerConfig.java | 19 +-- .../shedlock/test/support/jdbc/DbConfig.java | 14 +- .../shedlock/test/support/jdbc/H2Config.java | 14 +- .../test/support/jdbc/HsqlConfig.java | 14 +- .../test/support/jdbc/JdbcTestUtils.java | 40 +++-- .../test/support/jdbc/MariaDbConfig.java | 24 ++- .../test/support/jdbc/MsSqlServerConfig.java | 18 +-- .../test/support/jdbc/MySqlConfig.java | 23 ++- .../test/support/jdbc/OracleServerConfig.java | 15 +- .../test/support/jdbc/PostgresConfig.java | 20 ++- .../support/jdbc/TransactionalFuzzTester.java | 25 ++- .../memcached/spy/MemcachedLockProvider.java | 53 +++---- .../memcached/spy/MemcachedContainer.java | 4 +- .../MemcachedLockProviderIntegrationTest.java | 28 ++-- .../ReactiveStreamsMongoLockProvider.java | 118 +++++++-------- .../SingleLockableSubscriber.java | 24 ++- ...reamsMongoLockProviderIntegrationTest.java | 48 +++--- .../provider/mongo/MongoLockProvider.java | 114 +++++++------- .../MongoLockProviderIntegrationTest.java | 46 +++--- .../provider/neo4j/Neo4jLockProvider.java | 53 +++---- .../provider/neo4j/Neo4jStorageAccessor.java | 142 ++++++++++-------- .../Neo4jLockProviderIntegrationTest.java | 80 +++++----- .../provider/neo4j/Neo4jTestUtils.java | 58 +++---- .../opensearch/OpenSearchLockProvider.java | 119 +++++++-------- .../container/OpenSearchContainer.java | 19 ++- .../OpenSearchLockProviderTest.java | 50 +++--- .../r2dbc/AbstractR2dbcStorageAccessor.java | 128 ++++++++++------ .../shedlock/provider/r2dbc/R2dbcAdapter.java | 32 ++-- .../provider/r2dbc/R2dbcLockProvider.java | 31 ++-- .../provider/r2dbc/R2dbcStorageAccessor.java | 28 ++-- .../provider/r2dbc/AbstractR2dbcTest.java | 27 ++-- ...MariaR2dbcLockProviderIntegrationTest.java | 14 +- ...MsSqlR2dbcLockProviderIntegrationTest.java | 14 +- ...MySqlR2dbcLockProviderIntegrationTest.java | 14 +- ...racleR2dbcLockProviderIntegrationTest.java | 14 +- ...tgresR2dbcLockProviderIntegrationTest.java | 14 +- .../redis/jedis4/JedisLockProvider.java | 85 ++++++----- .../JedisLockProviderIntegrationTest.java | 26 ++-- .../provider/redis/jedis4/RedisContainer.java | 33 ++-- .../quarkus/QuarkusRedisLockProvider.java | 29 ++-- .../provider/redis/quarkus/LockedService.java | 8 +- ...QuarkusRedisLockProviderContainerTest.java | 7 +- ...arkusRedisLockProviderIntegrationTest.java | 10 +- .../redis/quarkus/SchedulerLockFactory.java | 6 +- .../spring/ReactiveRedisLockProvider.java | 71 ++++++--- .../redis/spring/RedisLockProvider.java | 93 +++++++----- ...ctiveRedisLockProviderIntegrationTest.java | 14 +- ...tractRedisLockProviderIntegrationTest.java | 29 ++-- ...pringRedisLockProviderIntegrationTest.java | 25 ++- .../curator/ZookeeperCuratorLockProvider.java | 46 +++--- ...perCuratorLockProviderIntegrationTest.java | 37 ++--- .../shedlock/core/AbstractSimpleLock.java | 20 +-- .../shedlock/core/ClockProvider.java | 18 +-- .../shedlock/core/DefaultLockManager.java | 29 ++-- .../core/DefaultLockingTaskExecutor.java | 43 +++--- .../shedlock/core/ExtensibleLockProvider.java | 21 +-- .../javacrumbs/shedlock/core/LockAssert.java | 39 +++-- .../shedlock/core/LockConfiguration.java | 48 +++--- .../core/LockConfigurationExtractor.java | 20 +-- .../shedlock/core/LockExtender.java | 29 ++-- .../javacrumbs/shedlock/core/LockManager.java | 18 +-- .../shedlock/core/LockProvider.java | 22 ++- .../shedlock/core/LockableRunnable.java | 14 +- .../shedlock/core/LockingTaskExecutor.java | 23 ++- .../javacrumbs/shedlock/core/SimpleLock.java | 31 ++-- .../support/AbstractStorageAccessor.java | 14 +- .../support/KeepAliveLockProvider.java | 67 +++++---- .../shedlock/support/LockException.java | 14 +- .../shedlock/support/LockRecordRegistry.java | 20 ++- .../shedlock/support/StorageAccessor.java | 25 +-- .../support/StorageBasedLockProvider.java | 62 ++++---- .../javacrumbs/shedlock/support/Utils.java | 44 +++--- .../shedlock/support/annotation/NonNull.java | 24 ++- .../support/annotation/NonNullApi.java | 17 ++- .../support/annotation/NonNullFields.java | 15 +- .../shedlock/support/annotation/Nullable.java | 27 ++-- .../shedlock/core/DefaultLockManagerTest.java | 34 ++--- .../core/DefaultLockingTaskExecutorTest.java | 42 +++--- .../shedlock/core/LockAssertTest.java | 32 ++-- .../shedlock/core/LockConfigurationTest.java | 30 ++-- .../shedlock/core/LockExtenderTest.java | 23 ++- .../shedlock/core/ReentrantLockProvider.java | 21 ++- .../core/ReentrantLockProviderTest.java | 42 +++--- .../support/KeepAliveLockProviderTest.java | 24 +-- .../support/LockRecordRegistryTest.java | 19 +-- .../support/StorageBasedLockProviderTest.java | 28 ++-- .../shedlock/support/UtilsTest.java | 20 +-- ...ExtensibleLockProviderIntegrationTest.java | 34 ++--- .../AbstractLockProviderIntegrationTest.java | 53 ++++--- ...orageBasedLockProviderIntegrationTest.java | 25 ++- .../shedlock/test/support/FuzzTester.java | 85 +++++------ .../ExtendedLockConfigurationExtractor.java | 23 ++- .../spring/LockableTaskScheduler.java | 30 ++-- .../annotation/EnableSchedulerLock.java | 82 +++++----- .../spring/annotation/SchedulerLock.java | 43 +++--- .../spring/aop/AbstractLockConfiguration.java | 18 +-- ...ckConfigurationExtractorConfiguration.java | 24 ++- .../aop/LockingNotSupportedException.java | 14 +- .../aop/MethodProxyLockConfiguration.java | 23 +-- .../aop/MethodProxyScheduledLockAdvisor.java | 44 +++--- ...sterDefaultTaskSchedulerPostProcessor.java | 55 ++++--- .../SchedulerLockConfigurationSelector.java | 39 +++-- .../aop/SchedulerProxyLockConfiguration.java | 21 ++- .../SchedulerProxyScheduledLockAdvisor.java | 19 +-- .../aop/SpringLockConfigurationExtractor.java | 104 +++++++------ .../spring/aop/StringToDurationConverter.java | 28 ++-- .../javacrumbs/shedlock/spring/TestUtils.java | 30 ++-- .../aop/AbstractSchedulerProxyTest.java | 55 +++---- ...tSpringLockConfigurationExtractorTest.java | 69 +++++---- .../shedlock/spring/aop/AopCleanupTest.java | 25 ++- .../shedlock/spring/aop/AopOrderingTest.java | 74 ++++----- .../spring/aop/MethodProxyAopConfig.java | 34 ++--- .../spring/aop/MethodProxyAopTest.java | 39 +++-- .../shedlock/spring/aop/MyScheduled.java | 21 ++- .../spring/aop/SchedulerProxyCglibTest.java | 36 +++-- .../SchedulerProxyDefaultSchedulerTest.java | 39 +++-- ...ScheduledExecutorServiceSchedulerTest.java | 37 +++-- .../spring/aop/SchedulerProxyTest.java | 32 ++-- .../SpringLockConfigurationExtractorTest.java | 77 +++------- .../aop/StringToDurationConverterTest.java | 27 ++-- .../spring/it/AbstractSchedulerConfig.java | 24 ++- .../spring/it/AbstractSchedulerTest.java | 25 ++- .../spring/it/ProxyIntegrationTest.java | 22 ++- .../spring/it/SchedulerIntegrationTest.java | 22 ++- .../shedlock/spring/proxytest/BeanImpl.java | 19 +-- .../spring/proxytest/BeanInterface.java | 14 +- .../spring/proxytest/DynamicProxyConfig.java | 15 +- .../spring/proxytest/SubclassProxyConfig.java | 15 +- .../shedlock/test/boot/Application.java | 17 +-- .../shedlock/test/boot/HelloController.java | 15 +- .../shedlock/test/boot/ScheduledTasks.java | 27 ++-- .../shedlock/test/boot/IntegrationTest.java | 26 ++-- .../shedlock/test/boot/Application.java | 14 +- .../shedlock/test/boot/HelloController.java | 15 +- .../shedlock/test/boot/ScheduledTasks.java | 21 ++- .../shedlock/test/boot/IntegrationTest.java | 24 ++- .../shedlock/test/boot/LockUnitTest.java | 14 +- .../shedlock/test/boot/Application.java | 17 +-- .../shedlock/test/boot/ScheduledTasks.java | 21 ++- .../shedlock/test/boot/IntegrationTest.java | 24 ++- .../shedlock/test/boot/Application.java | 17 +-- .../shedlock/test/boot/HelloController.java | 15 +- .../shedlock/test/boot/ScheduledTasks.java | 21 ++- .../shedlock/test/boot/IntegrationTest.java | 24 ++- .../shedlock/test/boot/LockUnitTest.java | 14 +- .../shedlock/test/boot/Application.java | 35 +++-- .../shedlock/test/boot/ScheduledTasks.java | 18 +-- .../shedlock/test/boot/IntegrationTest.java | 21 ++- 273 files changed, 4647 insertions(+), 5218 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6974674aa..f52e2f48b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -34,7 +34,7 @@ jobs: env: # Kotlin needs access to java.util MAVEN_OPTS: --add-opens java.base/java.util=ALL-UNNAMED - run: mvn test javadoc:javadoc + run: mvn test spotless:check javadoc:javadoc - name: Publish Test Report uses: mikepenz/action-junit-report@v4 if: always() # always run even if the previous step fails diff --git a/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/SchedulerLock.java b/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/SchedulerLock.java index 1de570832..94546f628 100644 --- a/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/SchedulerLock.java +++ b/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/SchedulerLock.java @@ -1,38 +1,45 @@ package net.javacrumbs.shedlock.cdi; -import javax.enterprise.util.Nonbinding; -import javax.interceptor.InterceptorBinding; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import javax.enterprise.util.Nonbinding; +import javax.interceptor.InterceptorBinding; @InterceptorBinding @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) @Inherited public @interface SchedulerLock { - /** - * Lock name. - */ - @Nonbinding String name(); + /** Lock name. */ + @Nonbinding + String name(); /** - * How long the lock should be kept in case the machine which obtained the lock died before releasing it. - * This is just a fallback, under normal circumstances the lock is released as soon the tasks finishes. Can be any format - * supported by Duration Conversion + * How long the lock should be kept in case the machine which obtained the lock + * died before releasing it. This is just a fallback, under normal circumstances + * the lock is released as soon the tasks finishes. Can be any format supported + * by Duration + * Conversion + * *

*/ - @Nonbinding String lockAtMostFor() default ""; + @Nonbinding + String lockAtMostFor() default ""; /** - * The lock will be held at least for this period of time. Can be used if you really need to execute the task - * at most once in given period of time. If the duration of the task is shorter than clock difference between nodes, the task can - * be theoretically executed more than once (one node after another). By setting this parameter, you can make sure that the - * lock will be kept at least for given period of time. Can be any format - * supported by Duration Conversion + * The lock will be held at least for this period of time. Can be used if you + * really need to execute the task at most once in given period of time. If the + * duration of the task is shorter than clock difference between nodes, the task + * can be theoretically executed more than once (one node after another). By + * setting this parameter, you can make sure that the lock will be kept at least + * for given period of time. Can be any format supported by Duration + * Conversion */ - @Nonbinding String lockAtLeastFor() default ""; + @Nonbinding + String lockAtLeastFor() default ""; } - diff --git a/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/CdiLockConfigurationExtractor.java b/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/CdiLockConfigurationExtractor.java index 3a5e54ab3..39d64de22 100644 --- a/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/CdiLockConfigurationExtractor.java +++ b/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/CdiLockConfigurationExtractor.java @@ -1,31 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.cdi.internal; - -import net.javacrumbs.shedlock.cdi.SchedulerLock; -import net.javacrumbs.shedlock.core.ClockProvider; -import net.javacrumbs.shedlock.core.LockConfiguration; +import static java.util.Objects.requireNonNull; +import static net.javacrumbs.shedlock.cdi.internal.Utils.parseDuration; import java.lang.reflect.Method; import java.time.Duration; import java.util.Optional; - -import static java.util.Objects.requireNonNull; -import static net.javacrumbs.shedlock.cdi.internal.Utils.parseDuration; +import net.javacrumbs.shedlock.cdi.SchedulerLock; +import net.javacrumbs.shedlock.core.ClockProvider; +import net.javacrumbs.shedlock.core.LockConfiguration; class CdiLockConfigurationExtractor { private final Duration defaultLockAtMostFor; @@ -36,7 +32,6 @@ class CdiLockConfigurationExtractor { this.defaultLockAtLeastFor = requireNonNull(defaultLockAtLeastFor); } - Optional getLockConfiguration(Method method) { Optional annotation = findAnnotation(method); return annotation.map(this::getLockConfiguration); @@ -44,11 +39,7 @@ Optional getLockConfiguration(Method method) { private LockConfiguration getLockConfiguration(SchedulerLock annotation) { return new LockConfiguration( - ClockProvider.now(), - getName(annotation), - getLockAtMostFor(annotation), - getLockAtLeastFor(annotation) - ); + ClockProvider.now(), getName(annotation), getLockAtMostFor(annotation), getLockAtLeastFor(annotation)); } private String getName(SchedulerLock annotation) { @@ -56,19 +47,11 @@ private String getName(SchedulerLock annotation) { } Duration getLockAtMostFor(SchedulerLock annotation) { - return getValue( - annotation.lockAtMostFor(), - this.defaultLockAtMostFor, - "lockAtMostFor" - ); + return getValue(annotation.lockAtMostFor(), this.defaultLockAtMostFor, "lockAtMostFor"); } Duration getLockAtLeastFor(SchedulerLock annotation) { - return getValue( - annotation.lockAtLeastFor(), - this.defaultLockAtLeastFor, - "lockAtLeastFor" - ); + return getValue(annotation.lockAtLeastFor(), this.defaultLockAtLeastFor, "lockAtLeastFor"); } private Duration getValue(String stringValueFromAnnotation, Duration defaultValue, String paramName) { @@ -83,5 +66,3 @@ Optional findAnnotation(Method method) { return Optional.ofNullable(method.getAnnotation(SchedulerLock.class)); } } - - diff --git a/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/LockingNotSupportedException.java b/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/LockingNotSupportedException.java index 7532ee44e..7dea76e24 100644 --- a/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/LockingNotSupportedException.java +++ b/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/LockingNotSupportedException.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.cdi.internal; diff --git a/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/SchedulerLockInterceptor.java b/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/SchedulerLockInterceptor.java index 129fad619..63a77cf5b 100644 --- a/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/SchedulerLockInterceptor.java +++ b/cdi/shedlock-cdi-vintage/src/main/java/net/javacrumbs/shedlock/cdi/internal/SchedulerLockInterceptor.java @@ -1,23 +1,21 @@ package net.javacrumbs.shedlock.cdi.internal; -import net.javacrumbs.shedlock.cdi.SchedulerLock; -import net.javacrumbs.shedlock.core.DefaultLockingTaskExecutor; -import net.javacrumbs.shedlock.core.LockConfiguration; -import net.javacrumbs.shedlock.core.LockProvider; -import net.javacrumbs.shedlock.core.LockingTaskExecutor; -import org.eclipse.microprofile.config.ConfigProvider; +import static net.javacrumbs.shedlock.cdi.internal.Utils.parseDuration; +import java.time.Duration; +import java.util.Objects; +import java.util.Optional; import javax.annotation.Priority; import javax.inject.Inject; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; - -import static net.javacrumbs.shedlock.cdi.internal.Utils.parseDuration; - +import net.javacrumbs.shedlock.cdi.SchedulerLock; +import net.javacrumbs.shedlock.core.DefaultLockingTaskExecutor; +import net.javacrumbs.shedlock.core.LockConfiguration; +import net.javacrumbs.shedlock.core.LockProvider; +import net.javacrumbs.shedlock.core.LockingTaskExecutor; +import org.eclipse.microprofile.config.ConfigProvider; @SchedulerLock(name = "?") @Priority(3001) @@ -33,9 +31,7 @@ public SchedulerLockInterceptor(LockProvider lockProvider) { String lockAtLeastFor = getConfigValue("shedlock.defaults.lock-at-least-for"); Objects.requireNonNull(lockAtMostFor, "shedlock.defaults.lock-at-most-for parameter is mandatory"); this.lockConfigurationExtractor = new CdiLockConfigurationExtractor( - parseDuration(lockAtMostFor), - lockAtLeastFor != null ? parseDuration(lockAtLeastFor) : Duration.ZERO - ); + parseDuration(lockAtMostFor), lockAtLeastFor != null ? parseDuration(lockAtLeastFor) : Duration.ZERO); } private static String getConfigValue(String propertyName) { @@ -49,7 +45,8 @@ Object lock(InvocationContext context) throws Throwable { throw new LockingNotSupportedException(); } - Optional lockConfiguration = lockConfigurationExtractor.getLockConfiguration(context.getMethod()); + Optional lockConfiguration = + lockConfigurationExtractor.getLockConfiguration(context.getMethod()); if (lockConfiguration.isPresent()) { lockingTaskExecutor.executeWithLock((LockingTaskExecutor.Task) context::proceed, lockConfiguration.get()); return null; diff --git a/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/SchedulerLock.java b/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/SchedulerLock.java index 74d131561..34845c168 100644 --- a/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/SchedulerLock.java +++ b/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/SchedulerLock.java @@ -2,7 +2,6 @@ import jakarta.enterprise.util.Nonbinding; import jakarta.interceptor.InterceptorBinding; - import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; @@ -14,26 +13,33 @@ @Target({ElementType.TYPE, ElementType.METHOD}) @Inherited public @interface SchedulerLock { - /** - * Lock name. - */ - @Nonbinding String name(); + /** Lock name. */ + @Nonbinding + String name(); /** - * How long the lock should be kept in case the machine which obtained the lock died before releasing it. - * This is just a fallback, under normal circumstances the lock is released as soon the tasks finishes. Can be any format - * supported by Duration Conversion + * How long the lock should be kept in case the machine which obtained the lock + * died before releasing it. This is just a fallback, under normal circumstances + * the lock is released as soon the tasks finishes. Can be any format supported + * by Duration + * Conversion + * *

*/ - @Nonbinding String lockAtMostFor() default ""; + @Nonbinding + String lockAtMostFor() default ""; /** - * The lock will be held at least for this period of time. Can be used if you really need to execute the task - * at most once in given period of time. If the duration of the task is shorter than clock difference between nodes, the task can - * be theoretically executed more than once (one node after another). By setting this parameter, you can make sure that the - * lock will be kept at least for given period of time. Can be any format - * supported by Duration Conversion + * The lock will be held at least for this period of time. Can be used if you + * really need to execute the task at most once in given period of time. If the + * duration of the task is shorter than clock difference between nodes, the task + * can be theoretically executed more than once (one node after another). By + * setting this parameter, you can make sure that the lock will be kept at least + * for given period of time. Can be any format supported by Duration + * Conversion */ - @Nonbinding String lockAtLeastFor() default ""; + @Nonbinding + String lockAtLeastFor() default ""; } - diff --git a/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/CdiLockConfigurationExtractor.java b/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/CdiLockConfigurationExtractor.java index 3a5e54ab3..39d64de22 100644 --- a/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/CdiLockConfigurationExtractor.java +++ b/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/CdiLockConfigurationExtractor.java @@ -1,31 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.cdi.internal; - -import net.javacrumbs.shedlock.cdi.SchedulerLock; -import net.javacrumbs.shedlock.core.ClockProvider; -import net.javacrumbs.shedlock.core.LockConfiguration; +import static java.util.Objects.requireNonNull; +import static net.javacrumbs.shedlock.cdi.internal.Utils.parseDuration; import java.lang.reflect.Method; import java.time.Duration; import java.util.Optional; - -import static java.util.Objects.requireNonNull; -import static net.javacrumbs.shedlock.cdi.internal.Utils.parseDuration; +import net.javacrumbs.shedlock.cdi.SchedulerLock; +import net.javacrumbs.shedlock.core.ClockProvider; +import net.javacrumbs.shedlock.core.LockConfiguration; class CdiLockConfigurationExtractor { private final Duration defaultLockAtMostFor; @@ -36,7 +32,6 @@ class CdiLockConfigurationExtractor { this.defaultLockAtLeastFor = requireNonNull(defaultLockAtLeastFor); } - Optional getLockConfiguration(Method method) { Optional annotation = findAnnotation(method); return annotation.map(this::getLockConfiguration); @@ -44,11 +39,7 @@ Optional getLockConfiguration(Method method) { private LockConfiguration getLockConfiguration(SchedulerLock annotation) { return new LockConfiguration( - ClockProvider.now(), - getName(annotation), - getLockAtMostFor(annotation), - getLockAtLeastFor(annotation) - ); + ClockProvider.now(), getName(annotation), getLockAtMostFor(annotation), getLockAtLeastFor(annotation)); } private String getName(SchedulerLock annotation) { @@ -56,19 +47,11 @@ private String getName(SchedulerLock annotation) { } Duration getLockAtMostFor(SchedulerLock annotation) { - return getValue( - annotation.lockAtMostFor(), - this.defaultLockAtMostFor, - "lockAtMostFor" - ); + return getValue(annotation.lockAtMostFor(), this.defaultLockAtMostFor, "lockAtMostFor"); } Duration getLockAtLeastFor(SchedulerLock annotation) { - return getValue( - annotation.lockAtLeastFor(), - this.defaultLockAtLeastFor, - "lockAtLeastFor" - ); + return getValue(annotation.lockAtLeastFor(), this.defaultLockAtLeastFor, "lockAtLeastFor"); } private Duration getValue(String stringValueFromAnnotation, Duration defaultValue, String paramName) { @@ -83,5 +66,3 @@ Optional findAnnotation(Method method) { return Optional.ofNullable(method.getAnnotation(SchedulerLock.class)); } } - - diff --git a/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/LockingNotSupportedException.java b/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/LockingNotSupportedException.java index 7532ee44e..7dea76e24 100644 --- a/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/LockingNotSupportedException.java +++ b/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/LockingNotSupportedException.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.cdi.internal; diff --git a/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/SchedulerLockInterceptor.java b/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/SchedulerLockInterceptor.java index 2b8ccb712..7cf483c64 100644 --- a/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/SchedulerLockInterceptor.java +++ b/cdi/shedlock-cdi/src/main/java/net/javacrumbs/shedlock/cdi/internal/SchedulerLockInterceptor.java @@ -1,10 +1,15 @@ package net.javacrumbs.shedlock.cdi.internal; +import static net.javacrumbs.shedlock.cdi.internal.Utils.parseDuration; + import jakarta.annotation.Priority; import jakarta.inject.Inject; import jakarta.interceptor.AroundInvoke; import jakarta.interceptor.Interceptor; import jakarta.interceptor.InvocationContext; +import java.time.Duration; +import java.util.Objects; +import java.util.Optional; import net.javacrumbs.shedlock.cdi.SchedulerLock; import net.javacrumbs.shedlock.core.DefaultLockingTaskExecutor; import net.javacrumbs.shedlock.core.LockConfiguration; @@ -12,13 +17,6 @@ import net.javacrumbs.shedlock.core.LockingTaskExecutor; import org.eclipse.microprofile.config.ConfigProvider; -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; - -import static net.javacrumbs.shedlock.cdi.internal.Utils.parseDuration; - - @SchedulerLock(name = "?") @Priority(3001) @Interceptor @@ -33,9 +31,7 @@ public SchedulerLockInterceptor(LockProvider lockProvider) { String lockAtLeastFor = getConfigValue("shedlock.defaults.lock-at-least-for"); Objects.requireNonNull(lockAtMostFor, "shedlock.defaults.lock-at-most-for parameter is mandatory"); this.lockConfigurationExtractor = new CdiLockConfigurationExtractor( - parseDuration(lockAtMostFor), - lockAtLeastFor != null ? parseDuration(lockAtLeastFor) : Duration.ZERO - ); + parseDuration(lockAtMostFor), lockAtLeastFor != null ? parseDuration(lockAtLeastFor) : Duration.ZERO); } private static String getConfigValue(String propertyName) { @@ -49,7 +45,8 @@ Object lock(InvocationContext context) throws Throwable { throw new LockingNotSupportedException(); } - Optional lockConfiguration = lockConfigurationExtractor.getLockConfiguration(context.getMethod()); + Optional lockConfiguration = + lockConfigurationExtractor.getLockConfiguration(context.getMethod()); if (lockConfiguration.isPresent()) { lockingTaskExecutor.executeWithLock((LockingTaskExecutor.Task) context::proceed, lockConfiguration.get()); return null; diff --git a/cdi/test/quarkus-test/src/main/java/QuarkusProdConfig.java b/cdi/test/quarkus-test/src/main/java/QuarkusProdConfig.java index df60bfedf..89bb78d25 100644 --- a/cdi/test/quarkus-test/src/main/java/QuarkusProdConfig.java +++ b/cdi/test/quarkus-test/src/main/java/QuarkusProdConfig.java @@ -1,11 +1,8 @@ import io.quarkus.arc.DefaultBean; import jakarta.enterprise.inject.Produces; import jakarta.inject.Singleton; -import net.javacrumbs.shedlock.core.LockConfiguration; -import net.javacrumbs.shedlock.core.LockProvider; -import net.javacrumbs.shedlock.core.SimpleLock; - import java.util.Optional; +import net.javacrumbs.shedlock.core.LockProvider; /* * Just to make the build to pass diff --git a/cdi/test/quarkus-test/src/test/java/net/javacrumbs/shedlock/quarkus/test/QuarkusConfig.java b/cdi/test/quarkus-test/src/test/java/net/javacrumbs/shedlock/quarkus/test/QuarkusConfig.java index c22cc92fb..27fe2a8ea 100644 --- a/cdi/test/quarkus-test/src/test/java/net/javacrumbs/shedlock/quarkus/test/QuarkusConfig.java +++ b/cdi/test/quarkus-test/src/test/java/net/javacrumbs/shedlock/quarkus/test/QuarkusConfig.java @@ -1,33 +1,29 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.quarkus.test; +import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; +import static org.mockito.Mockito.mock; import io.quarkus.arc.profile.IfBuildProfile; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Produces; import jakarta.inject.Singleton; +import java.io.IOException; import net.javacrumbs.shedlock.cdi.SchedulerLock; import net.javacrumbs.shedlock.core.LockProvider; -import java.io.IOException; - -import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; -import static org.mockito.Mockito.mock; - public class QuarkusConfig { @Produces @@ -37,7 +33,6 @@ public LockProvider lockProvider() { return mock(LockProvider.class); } - @ApplicationScoped static class TestBean { @@ -66,12 +61,9 @@ public int returnsValue() { } @SchedulerLock(name = "${property.value}", lockAtLeastFor = "${property.lock-at-least-for}") - public void property() { - - } + public void property() {} } - interface AnotherTestBean { void runManually(); } @@ -81,8 +73,6 @@ static class AnotherTestBeanImpl implements AnotherTestBean { @Override @SchedulerLock(name = "classAnnotation") - public void runManually() { - - } + public void runManually() {} } } diff --git a/cdi/test/quarkus-test/src/test/java/net/javacrumbs/shedlock/quarkus/test/QuarkusShedlockTest.java b/cdi/test/quarkus-test/src/test/java/net/javacrumbs/shedlock/quarkus/test/QuarkusShedlockTest.java index 25a12a15e..bec2a4fa4 100644 --- a/cdi/test/quarkus-test/src/test/java/net/javacrumbs/shedlock/quarkus/test/QuarkusShedlockTest.java +++ b/cdi/test/quarkus-test/src/test/java/net/javacrumbs/shedlock/quarkus/test/QuarkusShedlockTest.java @@ -1,22 +1,30 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.quarkus.test; +import static net.javacrumbs.shedlock.quarkus.test.TestUtils.hasParams; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + import io.quarkus.test.junit.QuarkusTest; import jakarta.inject.Inject; +import java.io.IOException; +import java.util.Optional; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.SimpleLock; import net.javacrumbs.shedlock.quarkus.test.QuarkusConfig.AnotherTestBean; @@ -27,18 +35,6 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.io.IOException; -import java.util.Optional; - -import static net.javacrumbs.shedlock.quarkus.test.TestUtils.hasParams; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - - @QuarkusTest class QuarkusShedlockTest { @Inject @@ -92,7 +88,9 @@ void shouldFailOnReturnType() { } @Test - @Disabled // Not implemented, waiting if anyone is going to use it. When needed, get the code from Quarkus SchedulerUtils + @Disabled // Not implemented, waiting if anyone is going to use it. When needed, get the + // code from + // Quarkus SchedulerUtils void shouldReadConfigurationProperty() { testBean.property(); verify(lockProvider).lock(hasParams("property", 30_000, 1_000)); diff --git a/cdi/test/quarkus-test/src/test/java/net/javacrumbs/shedlock/quarkus/test/TestUtils.java b/cdi/test/quarkus-test/src/test/java/net/javacrumbs/shedlock/quarkus/test/TestUtils.java index 5a76b6c19..ff5c0dae3 100644 --- a/cdi/test/quarkus-test/src/test/java/net/javacrumbs/shedlock/quarkus/test/TestUtils.java +++ b/cdi/test/quarkus-test/src/test/java/net/javacrumbs/shedlock/quarkus/test/TestUtils.java @@ -1,30 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.quarkus.test; +import static org.mockito.ArgumentMatchers.argThat; + +import java.time.Instant; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import org.mockito.ArgumentMatcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Instant; - -import static org.mockito.ArgumentMatchers.argThat; - public class TestUtils { private static final int GAP = 1000; @@ -36,14 +33,15 @@ public static LockConfiguration hasParams(String name, long lockAtMostFor, long @Override public boolean matches(LockConfiguration c) { return name.equals(c.getName()) - && isNearTo(lockAtMostFor, c.getLockAtMostUntil()) - && isNearTo(lockAtLeastFor, c.getLockAtLeastUntil()); + && isNearTo(lockAtMostFor, c.getLockAtMostUntil()) + && isNearTo(lockAtLeastFor, c.getLockAtLeastUntil()); } @Override public String toString() { Instant now = ClockProvider.now(); - return "hasParams(\"" + name + "\", " + now.plusMillis(lockAtMostFor) + ", " + now.plusMillis(lockAtLeastFor) + ")"; + return "hasParams(\"" + name + "\", " + now.plusMillis(lockAtMostFor) + ", " + + now.plusMillis(lockAtLeastFor) + ")"; } }); } diff --git a/micronaut/shedlock-micronaut/src/main/java/net/javacrumbs/shedlock/micronaut/SchedulerLock.java b/micronaut/shedlock-micronaut/src/main/java/net/javacrumbs/shedlock/micronaut/SchedulerLock.java index 5967da724..5384bacde 100644 --- a/micronaut/shedlock-micronaut/src/main/java/net/javacrumbs/shedlock/micronaut/SchedulerLock.java +++ b/micronaut/shedlock-micronaut/src/main/java/net/javacrumbs/shedlock/micronaut/SchedulerLock.java @@ -1,32 +1,28 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.micronaut; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import io.micronaut.aop.Around; import io.micronaut.context.annotation.Executable; import io.micronaut.context.annotation.Type; -import net.javacrumbs.shedlock.micronaut.internal.SchedulerLockInterceptor; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; +import net.javacrumbs.shedlock.micronaut.internal.SchedulerLockInterceptor; @Documented @Retention(RUNTIME) @@ -35,25 +31,30 @@ @Executable @Type(SchedulerLockInterceptor.class) public @interface SchedulerLock { - /** - * Lock name. - */ + /** Lock name. */ String name(); /** - * How long the lock should be kept in case the machine which obtained the lock died before releasing it. - * This is just a fallback, under normal circumstances the lock is released as soon the tasks finishes. Can be any format - * supported by Duration Conversion + * How long the lock should be kept in case the machine which obtained the lock + * died before releasing it. This is just a fallback, under normal circumstances + * the lock is released as soon the tasks finishes. Can be any format supported + * by Duration + * Conversion + * *

*/ String lockAtMostFor() default ""; /** - * The lock will be held at least for this period of time. Can be used if you really need to execute the task - * at most once in given period of time. If the duration of the task is shorter than clock difference between nodes, the task can - * be theoretically executed more than once (one node after another). By setting this parameter, you can make sure that the - * lock will be kept at least for given period of time. Can be any format - * supported by Duration Conversion + * The lock will be held at least for this period of time. Can be used if you + * really need to execute the task at most once in given period of time. If the + * duration of the task is shorter than clock difference between nodes, the task + * can be theoretically executed more than once (one node after another). By + * setting this parameter, you can make sure that the lock will be kept at least + * for given period of time. Can be any format supported by Duration + * Conversion */ String lockAtLeastFor() default ""; } diff --git a/micronaut/shedlock-micronaut/src/main/java/net/javacrumbs/shedlock/micronaut/internal/LockingNotSupportedException.java b/micronaut/shedlock-micronaut/src/main/java/net/javacrumbs/shedlock/micronaut/internal/LockingNotSupportedException.java index a9f7f7df7..fdd16259c 100644 --- a/micronaut/shedlock-micronaut/src/main/java/net/javacrumbs/shedlock/micronaut/internal/LockingNotSupportedException.java +++ b/micronaut/shedlock-micronaut/src/main/java/net/javacrumbs/shedlock/micronaut/internal/LockingNotSupportedException.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.micronaut.internal; diff --git a/micronaut/shedlock-micronaut/src/main/java/net/javacrumbs/shedlock/micronaut/internal/MicronautLockConfigurationExtractor.java b/micronaut/shedlock-micronaut/src/main/java/net/javacrumbs/shedlock/micronaut/internal/MicronautLockConfigurationExtractor.java index 47322919e..dc74be619 100644 --- a/micronaut/shedlock-micronaut/src/main/java/net/javacrumbs/shedlock/micronaut/internal/MicronautLockConfigurationExtractor.java +++ b/micronaut/shedlock-micronaut/src/main/java/net/javacrumbs/shedlock/micronaut/internal/MicronautLockConfigurationExtractor.java @@ -1,45 +1,42 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.micronaut.internal; +import static java.util.Objects.requireNonNull; + import io.micronaut.core.annotation.AnnotationValue; import io.micronaut.core.convert.ConversionService; import io.micronaut.core.util.StringUtils; import io.micronaut.inject.ExecutableMethod; +import java.time.Duration; +import java.util.Optional; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.micronaut.SchedulerLock; -import java.time.Duration; -import java.util.Optional; - -import static java.util.Objects.requireNonNull; - class MicronautLockConfigurationExtractor { private final Duration defaultLockAtMostFor; private final Duration defaultLockAtLeastFor; private final ConversionService conversionService; - MicronautLockConfigurationExtractor(Duration defaultLockAtMostFor, Duration defaultLockAtLeastFor, ConversionService conversionService) { + MicronautLockConfigurationExtractor( + Duration defaultLockAtMostFor, Duration defaultLockAtLeastFor, ConversionService conversionService) { this.defaultLockAtMostFor = requireNonNull(defaultLockAtMostFor); this.defaultLockAtLeastFor = requireNonNull(defaultLockAtLeastFor); this.conversionService = conversionService; } - Optional getLockConfiguration(ExecutableMethod method) { Optional> annotation = findAnnotation(method); return annotation.map(this::getLockConfiguration); @@ -47,11 +44,7 @@ Optional getLockConfiguration(ExecutableMethod annotation) { return new LockConfiguration( - ClockProvider.now(), - getName(annotation), - getLockAtMostFor(annotation), - getLockAtLeastFor(annotation) - ); + ClockProvider.now(), getName(annotation), getLockAtMostFor(annotation), getLockAtLeastFor(annotation)); } private String getName(AnnotationValue annotation) { @@ -59,26 +52,21 @@ private String getName(AnnotationValue annotation) { } Duration getLockAtMostFor(AnnotationValue annotation) { - return getValue( - annotation, - this.defaultLockAtMostFor, - "lockAtMostFor" - ); + return getValue(annotation, this.defaultLockAtMostFor, "lockAtMostFor"); } Duration getLockAtLeastFor(AnnotationValue annotation) { - return getValue( - annotation, - this.defaultLockAtLeastFor, - "lockAtLeastFor" - ); + return getValue(annotation, this.defaultLockAtLeastFor, "lockAtLeastFor"); } private Duration getValue(AnnotationValue annotation, Duration defaultValue, String paramName) { - String stringValueFromAnnotation = annotation.get(paramName, String.class).orElse(""); + String stringValueFromAnnotation = + annotation.get(paramName, String.class).orElse(""); if (StringUtils.hasText(stringValueFromAnnotation)) { - return conversionService.convert(stringValueFromAnnotation, Duration.class) - .orElseThrow(() -> new IllegalArgumentException("Invalid " + paramName + " value \"" + stringValueFromAnnotation + "\" - cannot parse into duration")); + return conversionService + .convert(stringValueFromAnnotation, Duration.class) + .orElseThrow(() -> new IllegalArgumentException("Invalid " + paramName + " value \"" + + stringValueFromAnnotation + "\" - cannot parse into duration")); } else { return defaultValue; } @@ -88,5 +76,3 @@ Optional> findAnnotation(ExecutableMethodLicensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.micronaut.internal; @@ -20,32 +18,34 @@ import io.micronaut.context.annotation.Value; import io.micronaut.core.convert.ConversionService; import jakarta.inject.Singleton; +import java.time.Duration; +import java.util.Optional; import net.javacrumbs.shedlock.core.DefaultLockingTaskExecutor; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.LockingTaskExecutor; -import java.time.Duration; -import java.util.Optional; - @Singleton public class SchedulerLockInterceptor implements MethodInterceptor { private final LockingTaskExecutor lockingTaskExecutor; private final MicronautLockConfigurationExtractor micronautLockConfigurationExtractor; public SchedulerLockInterceptor( - LockProvider lockProvider, - Optional> conversionService, - @Value("${shedlock.defaults.lock-at-most-for}") String defaultLockAtMostFor, - @Value("${shedlock.defaults.lock-at-least-for:PT0S}") String defaultLockAtLeastFor - ) { + LockProvider lockProvider, + Optional> conversionService, + @Value("${shedlock.defaults.lock-at-most-for}") String defaultLockAtMostFor, + @Value("${shedlock.defaults.lock-at-least-for:PT0S}") String defaultLockAtLeastFor) { ConversionService resolvedConversionService = conversionService.orElse(ConversionService.SHARED); lockingTaskExecutor = new DefaultLockingTaskExecutor(lockProvider); micronautLockConfigurationExtractor = new MicronautLockConfigurationExtractor( - resolvedConversionService.convert(defaultLockAtMostFor, Duration.class).orElseThrow(() -> new IllegalArgumentException("Invalid 'defaultLockAtMostFor' value")), - resolvedConversionService.convert(defaultLockAtLeastFor, Duration.class).orElseThrow(() -> new IllegalArgumentException("Invalid 'defaultLockAtLeastFor' value")), - resolvedConversionService); + resolvedConversionService + .convert(defaultLockAtMostFor, Duration.class) + .orElseThrow(() -> new IllegalArgumentException("Invalid 'defaultLockAtMostFor' value")), + resolvedConversionService + .convert(defaultLockAtLeastFor, Duration.class) + .orElseThrow(() -> new IllegalArgumentException("Invalid 'defaultLockAtLeastFor' value")), + resolvedConversionService); } @Override @@ -55,7 +55,8 @@ public Object intercept(MethodInvocationContext context) { throw new LockingNotSupportedException(); } - Optional lockConfiguration = micronautLockConfigurationExtractor.getLockConfiguration(context.getExecutableMethod()); + Optional lockConfiguration = + micronautLockConfigurationExtractor.getLockConfiguration(context.getExecutableMethod()); if (lockConfiguration.isPresent()) { lockingTaskExecutor.executeWithLock((Runnable) context::proceed, lockConfiguration.get()); return null; diff --git a/micronaut/shedlock-micronaut/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopConfig.java b/micronaut/shedlock-micronaut/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopConfig.java index d75966688..0a66a7d3e 100644 --- a/micronaut/shedlock-micronaut/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopConfig.java +++ b/micronaut/shedlock-micronaut/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopConfig.java @@ -1,31 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.micronaut.internal; +import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; +import static org.mockito.Mockito.mock; import io.micronaut.context.annotation.Factory; import jakarta.inject.Singleton; +import java.io.IOException; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.micronaut.SchedulerLock; -import java.io.IOException; - -import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; -import static org.mockito.Mockito.mock; - @Factory public class MethodProxyAopConfig { @@ -34,7 +30,6 @@ public LockProvider lockProvider() { return mock(LockProvider.class); } - @Singleton static class TestBean { @@ -63,12 +58,9 @@ public int returnsValue() { } @SchedulerLock(name = "${property.value}", lockAtLeastFor = "${property.lock-at-least-for}") - public void property() { - - } + public void property() {} } - interface AnotherTestBean { void runManually(); } @@ -78,8 +70,6 @@ static class AnotherTestBeanImpl implements AnotherTestBean { @Override @SchedulerLock(name = "classAnnotation") - public void runManually() { - - } + public void runManually() {} } } diff --git a/micronaut/shedlock-micronaut/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopTest.java b/micronaut/shedlock-micronaut/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopTest.java index c8eddf133..9e68726a7 100644 --- a/micronaut/shedlock-micronaut/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopTest.java +++ b/micronaut/shedlock-micronaut/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopTest.java @@ -1,22 +1,30 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.micronaut.internal; +import static net.javacrumbs.shedlock.micronaut.internal.TestUtils.hasParams; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import jakarta.inject.Inject; +import java.io.IOException; +import java.util.Optional; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.SimpleLock; import net.javacrumbs.shedlock.micronaut.internal.MethodProxyAopConfig.AnotherTestBean; @@ -25,18 +33,6 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.io.IOException; -import java.util.Optional; - -import static net.javacrumbs.shedlock.micronaut.internal.TestUtils.hasParams; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - - @MicronautTest class MethodProxyAopTest { @Inject diff --git a/micronaut/shedlock-micronaut/src/test/java/net/javacrumbs/shedlock/micronaut/internal/TestUtils.java b/micronaut/shedlock-micronaut/src/test/java/net/javacrumbs/shedlock/micronaut/internal/TestUtils.java index 66b9f743e..d5306f077 100644 --- a/micronaut/shedlock-micronaut/src/test/java/net/javacrumbs/shedlock/micronaut/internal/TestUtils.java +++ b/micronaut/shedlock-micronaut/src/test/java/net/javacrumbs/shedlock/micronaut/internal/TestUtils.java @@ -1,30 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.micronaut.internal; +import static org.mockito.ArgumentMatchers.argThat; + +import java.time.Instant; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import org.mockito.ArgumentMatcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Instant; - -import static org.mockito.ArgumentMatchers.argThat; - public class TestUtils { private static final int GAP = 1000; @@ -36,14 +33,15 @@ public static LockConfiguration hasParams(String name, long lockAtMostFor, long @Override public boolean matches(LockConfiguration c) { return name.equals(c.getName()) - && isNearTo(lockAtMostFor, c.getLockAtMostUntil()) - && isNearTo(lockAtLeastFor, c.getLockAtLeastUntil()); + && isNearTo(lockAtMostFor, c.getLockAtMostUntil()) + && isNearTo(lockAtLeastFor, c.getLockAtLeastUntil()); } @Override public String toString() { Instant now = ClockProvider.now(); - return "hasParams(\"" + name + "\", " + now.plusMillis(lockAtMostFor) + ", " + now.plusMillis(lockAtLeastFor) + ")"; + return "hasParams(\"" + name + "\", " + now.plusMillis(lockAtMostFor) + ", " + + now.plusMillis(lockAtLeastFor) + ")"; } }); } diff --git a/micronaut/shedlock-micronaut4/src/main/java/net/javacrumbs/shedlock/micronaut/SchedulerLock.java b/micronaut/shedlock-micronaut4/src/main/java/net/javacrumbs/shedlock/micronaut/SchedulerLock.java index 5967da724..5384bacde 100644 --- a/micronaut/shedlock-micronaut4/src/main/java/net/javacrumbs/shedlock/micronaut/SchedulerLock.java +++ b/micronaut/shedlock-micronaut4/src/main/java/net/javacrumbs/shedlock/micronaut/SchedulerLock.java @@ -1,32 +1,28 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.micronaut; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import io.micronaut.aop.Around; import io.micronaut.context.annotation.Executable; import io.micronaut.context.annotation.Type; -import net.javacrumbs.shedlock.micronaut.internal.SchedulerLockInterceptor; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; +import net.javacrumbs.shedlock.micronaut.internal.SchedulerLockInterceptor; @Documented @Retention(RUNTIME) @@ -35,25 +31,30 @@ @Executable @Type(SchedulerLockInterceptor.class) public @interface SchedulerLock { - /** - * Lock name. - */ + /** Lock name. */ String name(); /** - * How long the lock should be kept in case the machine which obtained the lock died before releasing it. - * This is just a fallback, under normal circumstances the lock is released as soon the tasks finishes. Can be any format - * supported by Duration Conversion + * How long the lock should be kept in case the machine which obtained the lock + * died before releasing it. This is just a fallback, under normal circumstances + * the lock is released as soon the tasks finishes. Can be any format supported + * by Duration + * Conversion + * *

*/ String lockAtMostFor() default ""; /** - * The lock will be held at least for this period of time. Can be used if you really need to execute the task - * at most once in given period of time. If the duration of the task is shorter than clock difference between nodes, the task can - * be theoretically executed more than once (one node after another). By setting this parameter, you can make sure that the - * lock will be kept at least for given period of time. Can be any format - * supported by Duration Conversion + * The lock will be held at least for this period of time. Can be used if you + * really need to execute the task at most once in given period of time. If the + * duration of the task is shorter than clock difference between nodes, the task + * can be theoretically executed more than once (one node after another). By + * setting this parameter, you can make sure that the lock will be kept at least + * for given period of time. Can be any format supported by Duration + * Conversion */ String lockAtLeastFor() default ""; } diff --git a/micronaut/shedlock-micronaut4/src/main/java/net/javacrumbs/shedlock/micronaut/internal/LockingNotSupportedException.java b/micronaut/shedlock-micronaut4/src/main/java/net/javacrumbs/shedlock/micronaut/internal/LockingNotSupportedException.java index a9f7f7df7..fdd16259c 100644 --- a/micronaut/shedlock-micronaut4/src/main/java/net/javacrumbs/shedlock/micronaut/internal/LockingNotSupportedException.java +++ b/micronaut/shedlock-micronaut4/src/main/java/net/javacrumbs/shedlock/micronaut/internal/LockingNotSupportedException.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.micronaut.internal; diff --git a/micronaut/shedlock-micronaut4/src/main/java/net/javacrumbs/shedlock/micronaut/internal/MicronautLockConfigurationExtractor.java b/micronaut/shedlock-micronaut4/src/main/java/net/javacrumbs/shedlock/micronaut/internal/MicronautLockConfigurationExtractor.java index 250246131..b8317c79a 100644 --- a/micronaut/shedlock-micronaut4/src/main/java/net/javacrumbs/shedlock/micronaut/internal/MicronautLockConfigurationExtractor.java +++ b/micronaut/shedlock-micronaut4/src/main/java/net/javacrumbs/shedlock/micronaut/internal/MicronautLockConfigurationExtractor.java @@ -1,45 +1,42 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.micronaut.internal; +import static java.util.Objects.requireNonNull; + import io.micronaut.core.annotation.AnnotationValue; import io.micronaut.core.convert.ConversionService; import io.micronaut.core.util.StringUtils; import io.micronaut.inject.ExecutableMethod; +import java.time.Duration; +import java.util.Optional; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.micronaut.SchedulerLock; -import java.time.Duration; -import java.util.Optional; - -import static java.util.Objects.requireNonNull; - class MicronautLockConfigurationExtractor { private final Duration defaultLockAtMostFor; private final Duration defaultLockAtLeastFor; private final ConversionService conversionService; - MicronautLockConfigurationExtractor(Duration defaultLockAtMostFor, Duration defaultLockAtLeastFor, ConversionService conversionService) { + MicronautLockConfigurationExtractor( + Duration defaultLockAtMostFor, Duration defaultLockAtLeastFor, ConversionService conversionService) { this.defaultLockAtMostFor = requireNonNull(defaultLockAtMostFor); this.defaultLockAtLeastFor = requireNonNull(defaultLockAtLeastFor); this.conversionService = conversionService; } - Optional getLockConfiguration(ExecutableMethod method) { Optional> annotation = findAnnotation(method); return annotation.map(this::getLockConfiguration); @@ -47,11 +44,7 @@ Optional getLockConfiguration(ExecutableMethod annotation) { return new LockConfiguration( - ClockProvider.now(), - getName(annotation), - getLockAtMostFor(annotation), - getLockAtLeastFor(annotation) - ); + ClockProvider.now(), getName(annotation), getLockAtMostFor(annotation), getLockAtLeastFor(annotation)); } private String getName(AnnotationValue annotation) { @@ -59,26 +52,21 @@ private String getName(AnnotationValue annotation) { } Duration getLockAtMostFor(AnnotationValue annotation) { - return getValue( - annotation, - this.defaultLockAtMostFor, - "lockAtMostFor" - ); + return getValue(annotation, this.defaultLockAtMostFor, "lockAtMostFor"); } Duration getLockAtLeastFor(AnnotationValue annotation) { - return getValue( - annotation, - this.defaultLockAtLeastFor, - "lockAtLeastFor" - ); + return getValue(annotation, this.defaultLockAtLeastFor, "lockAtLeastFor"); } private Duration getValue(AnnotationValue annotation, Duration defaultValue, String paramName) { - String stringValueFromAnnotation = annotation.get(paramName, String.class).orElse(""); + String stringValueFromAnnotation = + annotation.get(paramName, String.class).orElse(""); if (StringUtils.hasText(stringValueFromAnnotation)) { - return conversionService.convert(stringValueFromAnnotation, Duration.class) - .orElseThrow(() -> new IllegalArgumentException("Invalid " + paramName + " value \"" + stringValueFromAnnotation + "\" - cannot parse into duration")); + return conversionService + .convert(stringValueFromAnnotation, Duration.class) + .orElseThrow(() -> new IllegalArgumentException("Invalid " + paramName + " value \"" + + stringValueFromAnnotation + "\" - cannot parse into duration")); } else { return defaultValue; } @@ -88,5 +76,3 @@ Optional> findAnnotation(ExecutableMethodLicensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.micronaut.internal; @@ -20,43 +18,43 @@ import io.micronaut.context.annotation.Value; import io.micronaut.core.convert.ConversionService; import jakarta.inject.Singleton; +import java.time.Duration; +import java.util.Optional; import net.javacrumbs.shedlock.core.DefaultLockingTaskExecutor; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.LockingTaskExecutor; -import java.time.Duration; -import java.util.Optional; - @Singleton public class SchedulerLockInterceptor implements MethodInterceptor { private final LockingTaskExecutor lockingTaskExecutor; private final MicronautLockConfigurationExtractor micronautLockConfigurationExtractor; public SchedulerLockInterceptor( - LockProvider lockProvider, - Optional conversionService, - @Value("${shedlock.defaults.lock-at-most-for}") String defaultLockAtMostFor, - @Value("${shedlock.defaults.lock-at-least-for:PT0S}") String defaultLockAtLeastFor - ) { + LockProvider lockProvider, + Optional conversionService, + @Value("${shedlock.defaults.lock-at-most-for}") String defaultLockAtMostFor, + @Value("${shedlock.defaults.lock-at-least-for:PT0S}") String defaultLockAtLeastFor) { /* - * From Micronaut 3 to 4, ConversionService changes from a parameterized type to a - * non-parameterized one, so some raw type usage and unchecked casts are done to support - * both Micronaut versions. + * From Micronaut 3 to 4, ConversionService changes from a parameterized type to + * a non-parameterized one, so some raw type usage and unchecked casts are done + * to support both Micronaut versions. */ ConversionService resolvedConversionService = conversionService.orElse(ConversionService.SHARED); lockingTaskExecutor = new DefaultLockingTaskExecutor(lockProvider); micronautLockConfigurationExtractor = new MicronautLockConfigurationExtractor( - convert(resolvedConversionService, defaultLockAtMostFor, "defaultLockAtMostFor"), - convert(resolvedConversionService, defaultLockAtLeastFor, "defaultLockAtLeastFor"), - resolvedConversionService); + convert(resolvedConversionService, defaultLockAtMostFor, "defaultLockAtMostFor"), + convert(resolvedConversionService, defaultLockAtLeastFor, "defaultLockAtLeastFor"), + resolvedConversionService); } - private static Duration convert(ConversionService resolvedConversionService, String defaultLockAtMostFor, String label) { - return resolvedConversionService.convert(defaultLockAtMostFor, Duration.class) - .orElseThrow(() -> new IllegalArgumentException("Invalid '" + label + "' value")); + private static Duration convert( + ConversionService resolvedConversionService, String defaultLockAtMostFor, String label) { + return resolvedConversionService + .convert(defaultLockAtMostFor, Duration.class) + .orElseThrow(() -> new IllegalArgumentException("Invalid '" + label + "' value")); } @Override @@ -66,7 +64,8 @@ public Object intercept(MethodInvocationContext context) { throw new LockingNotSupportedException(); } - Optional lockConfiguration = micronautLockConfigurationExtractor.getLockConfiguration(context.getExecutableMethod()); + Optional lockConfiguration = + micronautLockConfigurationExtractor.getLockConfiguration(context.getExecutableMethod()); if (lockConfiguration.isPresent()) { lockingTaskExecutor.executeWithLock((Runnable) context::proceed, lockConfiguration.get()); return null; diff --git a/micronaut/shedlock-micronaut4/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopConfig.java b/micronaut/shedlock-micronaut4/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopConfig.java index d75966688..0a66a7d3e 100644 --- a/micronaut/shedlock-micronaut4/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopConfig.java +++ b/micronaut/shedlock-micronaut4/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopConfig.java @@ -1,31 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.micronaut.internal; +import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; +import static org.mockito.Mockito.mock; import io.micronaut.context.annotation.Factory; import jakarta.inject.Singleton; +import java.io.IOException; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.micronaut.SchedulerLock; -import java.io.IOException; - -import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; -import static org.mockito.Mockito.mock; - @Factory public class MethodProxyAopConfig { @@ -34,7 +30,6 @@ public LockProvider lockProvider() { return mock(LockProvider.class); } - @Singleton static class TestBean { @@ -63,12 +58,9 @@ public int returnsValue() { } @SchedulerLock(name = "${property.value}", lockAtLeastFor = "${property.lock-at-least-for}") - public void property() { - - } + public void property() {} } - interface AnotherTestBean { void runManually(); } @@ -78,8 +70,6 @@ static class AnotherTestBeanImpl implements AnotherTestBean { @Override @SchedulerLock(name = "classAnnotation") - public void runManually() { - - } + public void runManually() {} } } diff --git a/micronaut/shedlock-micronaut4/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopTest.java b/micronaut/shedlock-micronaut4/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopTest.java index c8eddf133..9e68726a7 100644 --- a/micronaut/shedlock-micronaut4/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopTest.java +++ b/micronaut/shedlock-micronaut4/src/test/java/net/javacrumbs/shedlock/micronaut/internal/MethodProxyAopTest.java @@ -1,22 +1,30 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.micronaut.internal; +import static net.javacrumbs.shedlock.micronaut.internal.TestUtils.hasParams; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import jakarta.inject.Inject; +import java.io.IOException; +import java.util.Optional; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.SimpleLock; import net.javacrumbs.shedlock.micronaut.internal.MethodProxyAopConfig.AnotherTestBean; @@ -25,18 +33,6 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.io.IOException; -import java.util.Optional; - -import static net.javacrumbs.shedlock.micronaut.internal.TestUtils.hasParams; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - - @MicronautTest class MethodProxyAopTest { @Inject diff --git a/micronaut/shedlock-micronaut4/src/test/java/net/javacrumbs/shedlock/micronaut/internal/TestUtils.java b/micronaut/shedlock-micronaut4/src/test/java/net/javacrumbs/shedlock/micronaut/internal/TestUtils.java index 66b9f743e..d5306f077 100644 --- a/micronaut/shedlock-micronaut4/src/test/java/net/javacrumbs/shedlock/micronaut/internal/TestUtils.java +++ b/micronaut/shedlock-micronaut4/src/test/java/net/javacrumbs/shedlock/micronaut/internal/TestUtils.java @@ -1,30 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.micronaut.internal; +import static org.mockito.ArgumentMatchers.argThat; + +import java.time.Instant; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import org.mockito.ArgumentMatcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Instant; - -import static org.mockito.ArgumentMatchers.argThat; - public class TestUtils { private static final int GAP = 1000; @@ -36,14 +33,15 @@ public static LockConfiguration hasParams(String name, long lockAtMostFor, long @Override public boolean matches(LockConfiguration c) { return name.equals(c.getName()) - && isNearTo(lockAtMostFor, c.getLockAtMostUntil()) - && isNearTo(lockAtLeastFor, c.getLockAtLeastUntil()); + && isNearTo(lockAtMostFor, c.getLockAtMostUntil()) + && isNearTo(lockAtLeastFor, c.getLockAtLeastUntil()); } @Override public String toString() { Instant now = ClockProvider.now(); - return "hasParams(\"" + name + "\", " + now.plusMillis(lockAtMostFor) + ", " + now.plusMillis(lockAtLeastFor) + ")"; + return "hasParams(\"" + name + "\", " + now.plusMillis(lockAtMostFor) + ", " + + now.plusMillis(lockAtLeastFor) + ")"; } }); } diff --git a/micronaut/test/micronaut-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Application.java b/micronaut/test/micronaut-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Application.java index b14c34d97..f058451a3 100644 --- a/micronaut/test/micronaut-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Application.java +++ b/micronaut/test/micronaut-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Application.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; @@ -22,4 +20,4 @@ public class Application { public static void main(String[] args) { Micronaut.run(Application.class); } -} \ No newline at end of file +} diff --git a/micronaut/test/micronaut-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Configuration.java b/micronaut/test/micronaut-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Configuration.java index 045212472..0427a753a 100644 --- a/micronaut/test/micronaut-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Configuration.java +++ b/micronaut/test/micronaut-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Configuration.java @@ -1,27 +1,24 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; import io.micronaut.context.annotation.Factory; import jakarta.inject.Singleton; +import javax.sql.DataSource; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider; -import javax.sql.DataSource; - @Factory public class Configuration { diff --git a/micronaut/test/micronaut-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java b/micronaut/test/micronaut-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java index 42410580e..701cd6623 100644 --- a/micronaut/test/micronaut-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java +++ b/micronaut/test/micronaut-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java @@ -1,28 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; +import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; + import io.micronaut.scheduling.annotation.Scheduled; import jakarta.inject.Singleton; -import net.javacrumbs.shedlock.micronaut.SchedulerLock; - import java.util.Date; import java.util.concurrent.atomic.AtomicBoolean; - -import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; +import net.javacrumbs.shedlock.micronaut.SchedulerLock; @Singleton public class ScheduledTasks { diff --git a/micronaut/test/micronaut-jdbc-template/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java b/micronaut/test/micronaut-jdbc-template/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java index bb303376c..fafae5461 100644 --- a/micronaut/test/micronaut-jdbc-template/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java +++ b/micronaut/test/micronaut-jdbc-template/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java @@ -1,27 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import jakarta.inject.Inject; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; - @MicronautTest public class ApplicationTest { @Inject diff --git a/micronaut/test/micronaut-jdbc/src/main/java/net/javacrumbs/micronaut/test/Application.java b/micronaut/test/micronaut-jdbc/src/main/java/net/javacrumbs/micronaut/test/Application.java index b14c34d97..f058451a3 100644 --- a/micronaut/test/micronaut-jdbc/src/main/java/net/javacrumbs/micronaut/test/Application.java +++ b/micronaut/test/micronaut-jdbc/src/main/java/net/javacrumbs/micronaut/test/Application.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; @@ -22,4 +20,4 @@ public class Application { public static void main(String[] args) { Micronaut.run(Application.class); } -} \ No newline at end of file +} diff --git a/micronaut/test/micronaut-jdbc/src/main/java/net/javacrumbs/micronaut/test/Configuration.java b/micronaut/test/micronaut-jdbc/src/main/java/net/javacrumbs/micronaut/test/Configuration.java index fdc92e0fc..292efb49e 100644 --- a/micronaut/test/micronaut-jdbc/src/main/java/net/javacrumbs/micronaut/test/Configuration.java +++ b/micronaut/test/micronaut-jdbc/src/main/java/net/javacrumbs/micronaut/test/Configuration.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; @@ -18,11 +16,10 @@ import io.micronaut.context.annotation.Factory; import io.micronaut.transaction.TransactionOperations; import jakarta.inject.Singleton; +import java.sql.Connection; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.provider.jdbc.micronaut.MicronautJdbcLockProvider; -import java.sql.Connection; - @Factory public class Configuration { diff --git a/micronaut/test/micronaut-jdbc/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java b/micronaut/test/micronaut-jdbc/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java index 42410580e..701cd6623 100644 --- a/micronaut/test/micronaut-jdbc/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java +++ b/micronaut/test/micronaut-jdbc/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java @@ -1,28 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; +import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; + import io.micronaut.scheduling.annotation.Scheduled; import jakarta.inject.Singleton; -import net.javacrumbs.shedlock.micronaut.SchedulerLock; - import java.util.Date; import java.util.concurrent.atomic.AtomicBoolean; - -import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; +import net.javacrumbs.shedlock.micronaut.SchedulerLock; @Singleton public class ScheduledTasks { diff --git a/micronaut/test/micronaut-jdbc/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java b/micronaut/test/micronaut-jdbc/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java index bb303376c..fafae5461 100644 --- a/micronaut/test/micronaut-jdbc/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java +++ b/micronaut/test/micronaut-jdbc/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java @@ -1,27 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import jakarta.inject.Inject; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; - @MicronautTest public class ApplicationTest { @Inject diff --git a/micronaut/test/micronaut4-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Application.java b/micronaut/test/micronaut4-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Application.java index b14c34d97..f058451a3 100644 --- a/micronaut/test/micronaut4-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Application.java +++ b/micronaut/test/micronaut4-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Application.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; @@ -22,4 +20,4 @@ public class Application { public static void main(String[] args) { Micronaut.run(Application.class); } -} \ No newline at end of file +} diff --git a/micronaut/test/micronaut4-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Configuration.java b/micronaut/test/micronaut4-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Configuration.java index 6c71ab2c5..1eba19b9f 100644 --- a/micronaut/test/micronaut4-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Configuration.java +++ b/micronaut/test/micronaut4-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/Configuration.java @@ -1,29 +1,26 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; import io.micronaut.context.annotation.Factory; import jakarta.inject.Singleton; +import javax.sql.DataSource; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.PlatformTransactionManager; -import javax.sql.DataSource; - @Factory public class Configuration { diff --git a/micronaut/test/micronaut4-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java b/micronaut/test/micronaut4-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java index 42410580e..701cd6623 100644 --- a/micronaut/test/micronaut4-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java +++ b/micronaut/test/micronaut4-jdbc-template/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java @@ -1,28 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; +import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; + import io.micronaut.scheduling.annotation.Scheduled; import jakarta.inject.Singleton; -import net.javacrumbs.shedlock.micronaut.SchedulerLock; - import java.util.Date; import java.util.concurrent.atomic.AtomicBoolean; - -import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; +import net.javacrumbs.shedlock.micronaut.SchedulerLock; @Singleton public class ScheduledTasks { diff --git a/micronaut/test/micronaut4-jdbc-template/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java b/micronaut/test/micronaut4-jdbc-template/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java index bb303376c..fafae5461 100644 --- a/micronaut/test/micronaut4-jdbc-template/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java +++ b/micronaut/test/micronaut4-jdbc-template/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java @@ -1,27 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import jakarta.inject.Inject; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; - @MicronautTest public class ApplicationTest { @Inject diff --git a/micronaut/test/micronaut4-jdbc/src/main/java/net/javacrumbs/micronaut/test/Application.java b/micronaut/test/micronaut4-jdbc/src/main/java/net/javacrumbs/micronaut/test/Application.java index b14c34d97..f058451a3 100644 --- a/micronaut/test/micronaut4-jdbc/src/main/java/net/javacrumbs/micronaut/test/Application.java +++ b/micronaut/test/micronaut4-jdbc/src/main/java/net/javacrumbs/micronaut/test/Application.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; @@ -22,4 +20,4 @@ public class Application { public static void main(String[] args) { Micronaut.run(Application.class); } -} \ No newline at end of file +} diff --git a/micronaut/test/micronaut4-jdbc/src/main/java/net/javacrumbs/micronaut/test/Configuration.java b/micronaut/test/micronaut4-jdbc/src/main/java/net/javacrumbs/micronaut/test/Configuration.java index fdc92e0fc..292efb49e 100644 --- a/micronaut/test/micronaut4-jdbc/src/main/java/net/javacrumbs/micronaut/test/Configuration.java +++ b/micronaut/test/micronaut4-jdbc/src/main/java/net/javacrumbs/micronaut/test/Configuration.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; @@ -18,11 +16,10 @@ import io.micronaut.context.annotation.Factory; import io.micronaut.transaction.TransactionOperations; import jakarta.inject.Singleton; +import java.sql.Connection; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.provider.jdbc.micronaut.MicronautJdbcLockProvider; -import java.sql.Connection; - @Factory public class Configuration { diff --git a/micronaut/test/micronaut4-jdbc/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java b/micronaut/test/micronaut4-jdbc/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java index 42410580e..701cd6623 100644 --- a/micronaut/test/micronaut4-jdbc/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java +++ b/micronaut/test/micronaut4-jdbc/src/main/java/net/javacrumbs/micronaut/test/ScheduledTasks.java @@ -1,28 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; +import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; + import io.micronaut.scheduling.annotation.Scheduled; import jakarta.inject.Singleton; -import net.javacrumbs.shedlock.micronaut.SchedulerLock; - import java.util.Date; import java.util.concurrent.atomic.AtomicBoolean; - -import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; +import net.javacrumbs.shedlock.micronaut.SchedulerLock; @Singleton public class ScheduledTasks { diff --git a/micronaut/test/micronaut4-jdbc/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java b/micronaut/test/micronaut4-jdbc/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java index bb303376c..fafae5461 100644 --- a/micronaut/test/micronaut4-jdbc/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java +++ b/micronaut/test/micronaut4-jdbc/src/test/java/net/javacrumbs/micronaut/test/ApplicationTest.java @@ -1,27 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.micronaut.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import jakarta.inject.Inject; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; - @MicronautTest public class ApplicationTest { @Inject diff --git a/pom.xml b/pom.xml index c98a45cf7..8847cd75d 100644 --- a/pom.xml +++ b/pom.xml @@ -92,6 +92,17 @@ + + com.diffplug.spotless + spotless-maven-plugin + 2.40.0 + + + 2.38.0 + + + + maven-compiler-plugin 3.11.0 diff --git a/providers/arangodb/shedlock-provider-arangodb/src/main/java/net/javacrumbs/shedlock/provider/arangodb/ArangoLockProvider.java b/providers/arangodb/shedlock-provider-arangodb/src/main/java/net/javacrumbs/shedlock/provider/arangodb/ArangoLockProvider.java index 1c8737157..a3a319c03 100644 --- a/providers/arangodb/shedlock-provider-arangodb/src/main/java/net/javacrumbs/shedlock/provider/arangodb/ArangoLockProvider.java +++ b/providers/arangodb/shedlock-provider-arangodb/src/main/java/net/javacrumbs/shedlock/provider/arangodb/ArangoLockProvider.java @@ -1,20 +1,20 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.arangodb; +import static net.javacrumbs.shedlock.support.Utils.getHostname; + import com.arangodb.ArangoCollection; import com.arangodb.ArangoDBException; import com.arangodb.ArangoDatabase; @@ -25,6 +25,8 @@ import com.arangodb.model.DocumentReadOptions; import com.arangodb.model.DocumentUpdateOptions; import com.arangodb.model.StreamTransactionOptions; +import java.time.Instant; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; @@ -34,15 +36,10 @@ import net.javacrumbs.shedlock.support.Utils; import net.javacrumbs.shedlock.support.annotation.NonNull; -import java.time.Instant; -import java.util.Optional; - -import static net.javacrumbs.shedlock.support.Utils.getHostname; - /** - * Arango Lock Provider needs existing collection - *
+ * Arango Lock Provider needs existing collection
* Example creating a collection through init scripts (javascript) + * *

  * db._useDatabase("DB_NAME");
  * db._create("COLLECTION_NAME");
@@ -60,7 +57,8 @@ public class ArangoLockProvider implements LockProvider {
     /**
      * Instantiates a new Arango lock provider.
      *
-     * @param arangoDatabase the arango database
+     * @param arangoDatabase
+     *            the arango database
      */
     public ArangoLockProvider(@NonNull ArangoDatabase arangoDatabase) {
         this(arangoDatabase.collection(COLLECTION_NAME));
@@ -69,7 +67,8 @@ public ArangoLockProvider(@NonNull ArangoDatabase arangoDatabase) {
     /**
      * Instantiates a new Arango lock provider.
      *
-     * @param arangoCollection the arango collection
+     * @param arangoCollection
+     *            the arango collection
      */
     public ArangoLockProvider(@NonNull ArangoCollection arangoCollection) {
         this.arangoCollection = arangoCollection;
@@ -82,31 +81,36 @@ public Optional lock(@NonNull LockConfiguration lockConfiguration) {
 
         try {
             /*
-                Transaction is necessary because repsert (insert with overwrite=true in arangodb)
-                is not possible with condition check (see case 2 description below)
+             * Transaction is necessary because repsert (insert with overwrite=true in
+             * arangodb) is not possible with condition check (see case 2 description below)
              */
-            StreamTransactionEntity streamTransactionEntity = arangoCollection.db().beginStreamTransaction(
-                new StreamTransactionOptions().exclusiveCollections(arangoCollection.name())
-            );
+            StreamTransactionEntity streamTransactionEntity = arangoCollection
+                    .db()
+                    .beginStreamTransaction(
+                            new StreamTransactionOptions().exclusiveCollections(arangoCollection.name()));
 
             transactionId = streamTransactionEntity.getId();
 
-            /*  There are three possible situations:
-                1. The lock document does not exist yet - insert document
-                2. The lock document exists and lockUtil <= now - update document
-                3. The lock document exists and lockUtil > now - nothing to do
+            /*
+             * There are three possible situations: 1. The lock document does not exist yet
+             * - insert document 2. The lock document exists and lockUtil <= now - update
+             * document 3. The lock document exists and lockUtil > now - nothing to do
              */
-            BaseDocument existingDocument = arangoCollection.getDocument(lockConfiguration.getName(),
-                BaseDocument.class, new DocumentReadOptions().streamTransactionId(transactionId));
+            BaseDocument existingDocument = arangoCollection.getDocument(
+                    lockConfiguration.getName(),
+                    BaseDocument.class,
+                    new DocumentReadOptions().streamTransactionId(transactionId));
 
             // 1. case
             if (existingDocument == null) {
-                BaseDocument newDocument = insertNewLock(transactionId, lockConfiguration.getName(), lockConfiguration.getLockAtMostUntil());
+                BaseDocument newDocument = insertNewLock(
+                        transactionId, lockConfiguration.getName(), lockConfiguration.getLockAtMostUntil());
                 return Optional.of(new ArangoLock(arangoCollection, newDocument, lockConfiguration));
             }
 
             // 2. case
-            Instant lockUntil = Instant.parse(existingDocument.getAttribute(LOCK_UNTIL).toString());
+            Instant lockUntil =
+                    Instant.parse(existingDocument.getAttribute(LOCK_UNTIL).toString());
             if (lockUntil.compareTo(ClockProvider.now()) <= 0) {
                 updateLockAtMostUntil(transactionId, existingDocument, lockConfiguration.getLockAtMostUntil());
                 return Optional.of(new ArangoLock(arangoCollection, existingDocument, lockConfiguration));
@@ -127,22 +131,23 @@ is not possible with condition check (see case 2 description below)
         }
     }
 
-    private BaseDocument insertNewLock(String transactionId, String documentKey, Instant lockAtMostUntil) throws ArangoDBException {
+    private BaseDocument insertNewLock(String transactionId, String documentKey, Instant lockAtMostUntil)
+            throws ArangoDBException {
         BaseDocument newDocument = new BaseDocument();
         newDocument.setKey(documentKey);
         setDocumentAttributes(newDocument, lockAtMostUntil);
-        DocumentCreateEntity document = arangoCollection.insertDocument(newDocument,
-            new DocumentCreateOptions().streamTransactionId(transactionId).returnNew(true)
-        );
+        DocumentCreateEntity document = arangoCollection.insertDocument(
+                newDocument,
+                new DocumentCreateOptions().streamTransactionId(transactionId).returnNew(true));
         return document.getNew();
     }
 
-    private void updateLockAtMostUntil(String transactionId,
-                                       BaseDocument existingDocument,
-                                       Instant lockAtMostUntil) {
+    private void updateLockAtMostUntil(String transactionId, BaseDocument existingDocument, Instant lockAtMostUntil) {
         setDocumentAttributes(existingDocument, lockAtMostUntil);
-        arangoCollection.updateDocument(existingDocument.getKey(), existingDocument,
-            new DocumentUpdateOptions().streamTransactionId(transactionId));
+        arangoCollection.updateDocument(
+                existingDocument.getKey(),
+                existingDocument,
+                new DocumentUpdateOptions().streamTransactionId(transactionId));
     }
 
     private void setDocumentAttributes(BaseDocument baseDocument, Instant lockAtMostUntil) {
@@ -156,9 +161,10 @@ private static final class ArangoLock extends AbstractSimpleLock {
         private final ArangoCollection arangoCollection;
         private final BaseDocument document;
 
-        public ArangoLock(final ArangoCollection arangoCollection,
-                          final BaseDocument document,
-                          final LockConfiguration lockConfiguration) {
+        public ArangoLock(
+                final ArangoCollection arangoCollection,
+                final BaseDocument document,
+                final LockConfiguration lockConfiguration) {
 
             super(lockConfiguration);
             this.arangoCollection = arangoCollection;
@@ -173,9 +179,6 @@ protected void doUnlock() {
             } catch (ArangoDBException e) {
                 throw new LockException("Unexpected error occured", e);
             }
-
         }
-
     }
-
 }
diff --git a/providers/arangodb/shedlock-provider-arangodb/src/test/java/net/javacrumbs/shedlock/provider/arangodb/ArangoLockProviderIntegrationTest.java b/providers/arangodb/shedlock-provider-arangodb/src/test/java/net/javacrumbs/shedlock/provider/arangodb/ArangoLockProviderIntegrationTest.java
index 7c647a6db..9cc50ed32 100644
--- a/providers/arangodb/shedlock-provider-arangodb/src/test/java/net/javacrumbs/shedlock/provider/arangodb/ArangoLockProviderIntegrationTest.java
+++ b/providers/arangodb/shedlock-provider-arangodb/src/test/java/net/javacrumbs/shedlock/provider/arangodb/ArangoLockProviderIntegrationTest.java
@@ -1,24 +1,30 @@
 /**
  * Copyright 2009 the original author or authors.
  *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * 

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.arangodb; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static net.javacrumbs.shedlock.provider.arangodb.ArangoLockProvider.COLLECTION_NAME; +import static net.javacrumbs.shedlock.provider.arangodb.ArangoLockProvider.LOCKED_AT; +import static net.javacrumbs.shedlock.provider.arangodb.ArangoLockProvider.LOCKED_BY; +import static net.javacrumbs.shedlock.provider.arangodb.ArangoLockProvider.LOCK_UNTIL; +import static org.assertj.core.api.Assertions.assertThat; + import com.arangodb.ArangoCollection; import com.arangodb.ArangoDB; import com.arangodb.ArangoDatabase; import com.arangodb.entity.BaseDocument; +import java.time.Instant; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.test.support.AbstractLockProviderIntegrationTest; import org.junit.jupiter.api.AfterAll; @@ -30,16 +36,6 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import java.time.Instant; - -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static net.javacrumbs.shedlock.provider.arangodb.ArangoLockProvider.COLLECTION_NAME; -import static net.javacrumbs.shedlock.provider.arangodb.ArangoLockProvider.LOCKED_AT; -import static net.javacrumbs.shedlock.provider.arangodb.ArangoLockProvider.LOCKED_BY; -import static net.javacrumbs.shedlock.provider.arangodb.ArangoLockProvider.LOCK_UNTIL; -import static org.assertj.core.api.Assertions.assertThat; - - @Testcontainers public class ArangoLockProviderIntegrationTest extends AbstractLockProviderIntegrationTest { @@ -62,11 +58,11 @@ static void beforeAll() { arangoContainer.start(); arango = new ArangoDB.Builder() - .host(DB_HOSTNAME, arangoContainer.getMappedPort(DB_PORT)) - .user(DB_USER) - .password(DB_PASSWORD) - .useSsl(false) - .build(); + .host(DB_HOSTNAME, arangoContainer.getMappedPort(DB_PORT)) + .user(DB_USER) + .password(DB_PASSWORD) + .useSsl(false) + .build(); if (!arango.getDatabases().contains(DB_NAME)) { arango.createDatabase(DB_NAME); @@ -75,7 +71,7 @@ static void beforeAll() { arangoDatabase = arango.db(DB_NAME); if (arangoDatabase.getCollections().stream() - .anyMatch(collectionEntity -> collectionEntity.getName().equals(COLLECTION_NAME))) { + .anyMatch(collectionEntity -> collectionEntity.getName().equals(COLLECTION_NAME))) { arangoCollection = arangoDatabase.collection(COLLECTION_NAME); arangoCollection.drop(); } diff --git a/providers/cassandra/shedlock-provider-cassandra/src/main/java/net/javacrumbs/shedlock/provider/cassandra/CassandraLockProvider.java b/providers/cassandra/shedlock-provider-cassandra/src/main/java/net/javacrumbs/shedlock/provider/cassandra/CassandraLockProvider.java index 7f12829ce..9d022f6c9 100644 --- a/providers/cassandra/shedlock-provider-cassandra/src/main/java/net/javacrumbs/shedlock/provider/cassandra/CassandraLockProvider.java +++ b/providers/cassandra/shedlock-provider-cassandra/src/main/java/net/javacrumbs/shedlock/provider/cassandra/CassandraLockProvider.java @@ -1,28 +1,26 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.cassandra; +import static java.util.Objects.requireNonNull; + import com.datastax.oss.driver.api.core.ConsistencyLevel; import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.CqlSession; import net.javacrumbs.shedlock.support.StorageBasedLockProvider; import net.javacrumbs.shedlock.support.annotation.NonNull; -import static java.util.Objects.requireNonNull; - /** * Cassandra Lock Provider needs a keyspace and uses a lock table
* Example creating keyspace and table @@ -39,17 +37,20 @@ public CassandraLockProvider(@NonNull CqlSession cqlSession) { this(cqlSession, DEFAULT_TABLE, ConsistencyLevel.QUORUM); } - public CassandraLockProvider(@NonNull CqlSession cqlSession, @NonNull String table, @NonNull ConsistencyLevel consistencyLevel) { - this(Configuration.builder().withCqlSession(cqlSession).withTableName(table).withConsistencyLevel(consistencyLevel).build()); + public CassandraLockProvider( + @NonNull CqlSession cqlSession, @NonNull String table, @NonNull ConsistencyLevel consistencyLevel) { + this(Configuration.builder() + .withCqlSession(cqlSession) + .withTableName(table) + .withConsistencyLevel(consistencyLevel) + .build()); } public CassandraLockProvider(@NonNull Configuration configuration) { super(new CassandraStorageAccessor(configuration)); } - /** - * Convenience class to specify configuration - */ + /** Convenience class to specify configuration */ public static final class Configuration { private final CqlIdentifier table; private final ColumnNames columnNames; @@ -59,18 +60,18 @@ public static final class Configuration { private final CqlIdentifier keyspace; Configuration( - @NonNull CqlSession cqlSession, - @NonNull CqlIdentifier table, - @NonNull ColumnNames columnNames, - @NonNull ConsistencyLevel consistencyLevel, - @NonNull ConsistencyLevel serialConsistencyLevel, - CqlIdentifier keyspace - ) { + @NonNull CqlSession cqlSession, + @NonNull CqlIdentifier table, + @NonNull ColumnNames columnNames, + @NonNull ConsistencyLevel consistencyLevel, + @NonNull ConsistencyLevel serialConsistencyLevel, + CqlIdentifier keyspace) { this.table = requireNonNull(table, "table can not be null"); this.columnNames = requireNonNull(columnNames, "columnNames can not be null"); this.cqlSession = requireNonNull(cqlSession, "cqlSession can not be null"); this.consistencyLevel = requireNonNull(consistencyLevel, "consistencyLevel can not be null"); - this.serialConsistencyLevel = requireNonNull(serialConsistencyLevel, "serialConsistencyLevel can not be null"); + this.serialConsistencyLevel = + requireNonNull(serialConsistencyLevel, "serialConsistencyLevel can not be null"); this.keyspace = keyspace; } @@ -102,9 +103,7 @@ public static Configuration.Builder builder() { return new Configuration.Builder(); } - /** - * Convenience builder class to build Configuration - */ + /** Convenience builder class to build Configuration */ public static final class Builder { private CqlIdentifier table = CqlIdentifier.fromCql(DEFAULT_TABLE); private ColumnNames columnNames = new ColumnNames("name", "lockUntil", "lockedAt", "lockedBy"); @@ -138,11 +137,11 @@ public Builder withConsistencyLevel(@NonNull ConsistencyLevel consistencyLevel) } /** - * Since Shedlock internally uses CAS (Compare And Set) operations - * This configuration helps to have a granular control on the CAS consistency. + * Since Shedlock internally uses CAS (Compare And Set) operations This + * configuration helps to have a granular control on the CAS consistency. + * * @return Builder */ - public Builder withSerialConsistencyLevel(@NonNull ConsistencyLevel serialConsistencyLevel) { this.serialConsistencyLevel = serialConsistencyLevel; return this; @@ -154,14 +153,13 @@ public Builder withKeyspace(@NonNull CqlIdentifier keyspace) { } public CassandraLockProvider.Configuration build() { - return new CassandraLockProvider.Configuration(cqlSession, table, columnNames, consistencyLevel, serialConsistencyLevel, keyspace); + return new CassandraLockProvider.Configuration( + cqlSession, table, columnNames, consistencyLevel, serialConsistencyLevel, keyspace); } } } - /** - * Convenience class to specify column names - */ + /** Convenience class to specify column names */ public static final class ColumnNames { private final String lockName; private final String lockUntil; @@ -169,7 +167,8 @@ public static final class ColumnNames { private final String lockedBy; /** - * Each column names are optional and if not specified the default column name would be considered. + * Each column names are optional and if not specified the default column name + * would be considered. */ public ColumnNames(String lockName, String lockUntil, String lockedAt, String lockedBy) { this.lockName = requireNonNull(lockName, "'lockName' column name can not be null"); diff --git a/providers/cassandra/shedlock-provider-cassandra/src/main/java/net/javacrumbs/shedlock/provider/cassandra/CassandraStorageAccessor.java b/providers/cassandra/shedlock-provider-cassandra/src/main/java/net/javacrumbs/shedlock/provider/cassandra/CassandraStorageAccessor.java index 3e69f609d..a8a976fb5 100644 --- a/providers/cassandra/shedlock-provider-cassandra/src/main/java/net/javacrumbs/shedlock/provider/cassandra/CassandraStorageAccessor.java +++ b/providers/cassandra/shedlock-provider-cassandra/src/main/java/net/javacrumbs/shedlock/provider/cassandra/CassandraStorageAccessor.java @@ -1,20 +1,21 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.cassandra; +import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.literal; +import static java.util.Objects.requireNonNull; + import com.datastax.oss.driver.api.core.ConsistencyLevel; import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.CqlSession; @@ -23,6 +24,8 @@ import com.datastax.oss.driver.api.core.cql.SimpleStatement; import com.datastax.oss.driver.api.core.servererrors.QueryExecutionException; import com.datastax.oss.driver.api.querybuilder.QueryBuilder; +import java.time.Instant; +import java.util.Optional; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.provider.cassandra.CassandraLockProvider.Configuration; @@ -30,18 +33,11 @@ import net.javacrumbs.shedlock.support.Utils; import net.javacrumbs.shedlock.support.annotation.NonNull; -import java.time.Instant; -import java.util.Optional; - -import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.literal; -import static java.util.Objects.requireNonNull; - -/** - * StorageAccessor for cassandra. - **/ +/** StorageAccessor for cassandra. */ /* - * In theory, all the reads (find() method calls) in update methods are not necessary, - * but it's a performance optimization. Moreover, the fuzzTest sometimes fails without them. + * In theory, all the reads (find() method calls) in update methods are not + * necessary, but it's a performance optimization. Moreover, the fuzzTest + * sometimes fails without them. */ class CassandraStorageAccessor extends AbstractStorageAccessor { private final String hostname; @@ -106,7 +102,9 @@ public void unlock(@NonNull LockConfiguration lockConfiguration) { @Override public boolean extend(@NonNull LockConfiguration lockConfiguration) { Optional lock = find(lockConfiguration.getName()); - if (lock.isEmpty() || lock.get().lockUntil().isBefore(ClockProvider.now()) || !lock.get().lockedBy().equals(hostname)) { + if (lock.isEmpty() + || lock.get().lockUntil().isBefore(ClockProvider.now()) + || !lock.get().lockedBy().equals(hostname)) { logger.trace("extend false"); return false; } @@ -117,18 +115,20 @@ public boolean extend(@NonNull LockConfiguration lockConfiguration) { /** * Find existing row by primary key lock.name * - * @param name lock name + * @param name + * lock name * @return optional lock row or empty */ Optional find(String name) { SimpleStatement selectStatement = QueryBuilder.selectFrom(keyspace, table) - .column(lockUntil) - .column(lockedAt) - .column(lockedBy) - .whereColumn(lockName).isEqualTo(literal(name)) - .build() - .setConsistencyLevel(consistencyLevel) - .setSerialConsistencyLevel(serialConsistencyLevel); + .column(lockUntil) + .column(lockedAt) + .column(lockedBy) + .whereColumn(lockName) + .isEqualTo(literal(name)) + .build() + .setConsistencyLevel(consistencyLevel) + .setSerialConsistencyLevel(serialConsistencyLevel); ResultSet resultSet = cqlSession.execute(selectStatement); Row row = resultSet.one(); @@ -142,52 +142,66 @@ Optional find(String name) { /** * Insert new lock row * - * @param name lock name - * @param until new until instant value + * @param name + * lock name + * @param until + * new until instant value */ private boolean insert(String name, Instant until) { return execute(QueryBuilder.insertInto(keyspace, table) - .value(lockName, literal(name)) - .value(lockUntil, literal(until)) - .value(lockedAt, literal(ClockProvider.now())) - .value(lockedBy, literal(hostname)) - .ifNotExists() - .build()); + .value(lockName, literal(name)) + .value(lockUntil, literal(until)) + .value(lockedAt, literal(ClockProvider.now())) + .value(lockedBy, literal(hostname)) + .ifNotExists() + .build()); } /** * Update existing lock row * - * @param name lock name - * @param until new until instant value + * @param name + * lock name + * @param until + * new until instant value */ private boolean update(String name, Instant until) { return execute(QueryBuilder.update(keyspace, table) - .setColumn(lockUntil, literal(until)) - .setColumn(lockedAt, literal(ClockProvider.now())) - .setColumn(lockedBy, literal(hostname)) - .whereColumn(lockName).isEqualTo(literal(name)) - .ifColumn(lockUntil).isLessThan(literal(ClockProvider.now())) - .build()); + .setColumn(lockUntil, literal(until)) + .setColumn(lockedAt, literal(ClockProvider.now())) + .setColumn(lockedBy, literal(hostname)) + .whereColumn(lockName) + .isEqualTo(literal(name)) + .ifColumn(lockUntil) + .isLessThan(literal(ClockProvider.now())) + .build()); } /** * Updates lock.until field where lockConfiguration.name * - * @param name lock name - * @param until new until instant value + * @param name + * lock name + * @param until + * new until instant value */ private boolean updateUntil(String name, Instant until) { return execute(QueryBuilder.update(keyspace, table) - .setColumn(lockUntil, literal(until)) - .whereColumn(lockName).isEqualTo(literal(name)) - .ifColumn(lockUntil).isGreaterThanOrEqualTo(literal(ClockProvider.now())) - .ifColumn(lockedBy).isEqualTo(literal(hostname)) - .build()); + .setColumn(lockUntil, literal(until)) + .whereColumn(lockName) + .isEqualTo(literal(name)) + .ifColumn(lockUntil) + .isGreaterThanOrEqualTo(literal(ClockProvider.now())) + .ifColumn(lockedBy) + .isEqualTo(literal(hostname)) + .build()); } - private boolean execute(SimpleStatement statement) { - return cqlSession.execute(statement.setConsistencyLevel(consistencyLevel).setSerialConsistencyLevel(serialConsistencyLevel)).wasApplied(); + return cqlSession + .execute(statement + .setConsistencyLevel(consistencyLevel) + .setSerialConsistencyLevel(serialConsistencyLevel)) + .wasApplied(); } } diff --git a/providers/cassandra/shedlock-provider-cassandra/src/main/java/net/javacrumbs/shedlock/provider/cassandra/Lock.java b/providers/cassandra/shedlock-provider-cassandra/src/main/java/net/javacrumbs/shedlock/provider/cassandra/Lock.java index 11d24919b..329c220ad 100644 --- a/providers/cassandra/shedlock-provider-cassandra/src/main/java/net/javacrumbs/shedlock/provider/cassandra/Lock.java +++ b/providers/cassandra/shedlock-provider-cassandra/src/main/java/net/javacrumbs/shedlock/provider/cassandra/Lock.java @@ -1,21 +1,18 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.cassandra; import java.time.Instant; -record Lock(Instant lockUntil, Instant lockedAt, String lockedBy) { -} +record Lock(Instant lockUntil, Instant lockedAt, String lockedBy) {} diff --git a/providers/cassandra/shedlock-provider-cassandra/src/test/java/net/javacrumbs/shedlock/provider/cassandra/CassandraLockProviderIntegrationTest.java b/providers/cassandra/shedlock-provider-cassandra/src/test/java/net/javacrumbs/shedlock/provider/cassandra/CassandraLockProviderIntegrationTest.java index 20d81a4e2..a16293152 100644 --- a/providers/cassandra/shedlock-provider-cassandra/src/test/java/net/javacrumbs/shedlock/provider/cassandra/CassandraLockProviderIntegrationTest.java +++ b/providers/cassandra/shedlock-provider-cassandra/src/test/java/net/javacrumbs/shedlock/provider/cassandra/CassandraLockProviderIntegrationTest.java @@ -1,23 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.cassandra; +import static com.datastax.oss.driver.api.core.CqlIdentifier.fromCql; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static net.javacrumbs.shedlock.provider.cassandra.CassandraLockProvider.DEFAULT_TABLE; +import static org.assertj.core.api.Assertions.assertThat; + import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.querybuilder.QueryBuilder; +import java.net.InetSocketAddress; import net.javacrumbs.shedlock.provider.cassandra.CassandraLockProvider.Configuration; import net.javacrumbs.shedlock.support.StorageBasedLockProvider; import net.javacrumbs.shedlock.test.support.AbstractStorageBasedLockProviderIntegrationTest; @@ -27,15 +31,9 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import java.net.InetSocketAddress; - -import static com.datastax.oss.driver.api.core.CqlIdentifier.fromCql; -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static net.javacrumbs.shedlock.provider.cassandra.CassandraLockProvider.DEFAULT_TABLE; -import static org.assertj.core.api.Assertions.assertThat; - /** - * Integration test uses local instance of Cassandra running on localhost at port 9042 using keyspace shedlock and table lock + * Integration test uses local instance of Cassandra running on localhost at + * port 9042 using keyspace shedlock and table lock * * @see net.javacrumbs.shedlock.provider.cassandra.CassandraLockProvider */ @@ -46,9 +44,9 @@ public class CassandraLockProviderIntegrationTest extends AbstractStorageBasedLo @Container public static final MyCassandraContainer cassandra = new MyCassandraContainer() - .withInitScript("shedlock.cql") - .withEnv("CASSANDRA_DC", "local") - .withEnv("CASSANDRA_ENDPOINT_SNITCH", "GossipingPropertyFileSnitch"); + .withInitScript("shedlock.cql") + .withEnv("CASSANDRA_DC", "local") + .withEnv("CASSANDRA_ENDPOINT_SNITCH", "GossipingPropertyFileSnitch"); @BeforeAll public static void startCassandra() { @@ -57,9 +55,9 @@ public static void startCassandra() { InetSocketAddress containerEndPoint = new InetSocketAddress(containerIpAddress, containerPort); session = CqlSession.builder() - .addContactPoint(containerEndPoint) - .withLocalDatacenter("local") - .build(); + .addContactPoint(containerEndPoint) + .withLocalDatacenter("local") + .build(); } @AfterEach @@ -69,12 +67,10 @@ public void after() { @Override protected StorageBasedLockProvider getLockProvider() { - return new CassandraLockProvider( - Configuration.builder() + return new CassandraLockProvider(Configuration.builder() .withCqlSession(session) .withKeyspace(KEYSPACE) - .build() - ); + .build()); } @Override @@ -94,9 +90,11 @@ protected void assertLocked(String lockName) { } private Lock findLock(String lockName) { - CassandraStorageAccessor cassandraStorageAccessor = new CassandraStorageAccessor( - Configuration.builder().withCqlSession(session).withKeyspace(KEYSPACE).withTableName(DEFAULT_TABLE).build() - ); + CassandraStorageAccessor cassandraStorageAccessor = new CassandraStorageAccessor(Configuration.builder() + .withCqlSession(session) + .withKeyspace(KEYSPACE) + .withTableName(DEFAULT_TABLE) + .build()); return cassandraStorageAccessor.find(lockName).get(); } diff --git a/providers/consul/shedlock-provider-consul/src/main/java/net/javacrumbs/shedlock/provider/consul/ConsulLockProvider.java b/providers/consul/shedlock-provider-consul/src/main/java/net/javacrumbs/shedlock/provider/consul/ConsulLockProvider.java index e3c1ed0de..3cab8e84c 100644 --- a/providers/consul/shedlock-provider-consul/src/main/java/net/javacrumbs/shedlock/provider/consul/ConsulLockProvider.java +++ b/providers/consul/shedlock-provider-consul/src/main/java/net/javacrumbs/shedlock/provider/consul/ConsulLockProvider.java @@ -1,25 +1,31 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.consul; +import static java.util.Objects.requireNonNull; +import static net.javacrumbs.shedlock.core.ClockProvider.now; + import com.ecwid.consul.v1.ConsulClient; import com.ecwid.consul.v1.QueryParams; import com.ecwid.consul.v1.kv.model.PutParams; import com.ecwid.consul.v1.session.model.NewSession; import com.ecwid.consul.v1.session.model.Session; +import java.time.Duration; +import java.util.Optional; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.SimpleLock; @@ -27,28 +33,28 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Duration; -import java.util.Optional; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import static java.util.Objects.requireNonNull; -import static net.javacrumbs.shedlock.core.ClockProvider.now; - /** - *

This lock provider registers a new session for lock and on unlock this session is removed together with all associated locks.

+ * This lock provider registers a new session for lock and on unlock this + * session is removed together with all associated locks. * - *

The main point you need to be aware about is that consul holds session for up to twice TTL. That means, - * even if the session TTL is set to 10 seconds, consul will hold still this session for 20 seconds. - * This is an expected behaviour and it's impossible to change it. - * This is the reason consul recommends to set the lowest possible TTL - * and constantly extend it. With this lock it means that even if your lockAtMostFor is less that 20 seconds, the timeout will be - * higher than 10 seconds and most likely will be 20.

+ *

+ * The main point you need to be aware about is that consul holds session for up + * to twice TTL. That means, even if the session TTL is set to 10 seconds, + * consul will hold still this session for 20 seconds. This is an + * expected + * behaviour and it's impossible to change it. This is the reason consul + * recommends to set + * the lowest possible TTL and constantly extend it. With this lock it means + * that even if your lockAtMostFor is less that 20 seconds, the timeout will be + * higher than 10 seconds and most likely will be 20. * - *

The lock is acquired for the time specified in {@code @SchedulerLock.lockAtMostFor}. Please note that this lock provider - * doesn't make any correction to the aforementioned TTL behaviour so most likely your locked session will live for - * longer than specified in lockAtMostFor. In this lock provider there is no session renewal done in the background.

+ *

+ * The lock is acquired for the time specified in + * {@code @SchedulerLock.lockAtMostFor}. Please note that this lock provider + * doesn't make any correction to the aforementioned TTL behaviour so most + * likely your locked session will live for longer than specified in + * lockAtMostFor. In this lock provider there is no session renewal done in the + * background. * * @author Artur Kalimullin */ @@ -64,32 +70,27 @@ public class ConsulLockProvider implements LockProvider, AutoCloseable { private final Configuration configuration; public ConsulLockProvider(@NonNull ConsulClient consulClient) { - this(Configuration.builder() - .withConsulClient(consulClient) - .build() - ); + this(Configuration.builder().withConsulClient(consulClient).build()); } public ConsulLockProvider(@NonNull ConsulClient consulClient, Duration minSessionTtl) { this(Configuration.builder() - .withConsulClient(consulClient) - .withMinSessionTtl(minSessionTtl) - .build() - ); + .withConsulClient(consulClient) + .withMinSessionTtl(minSessionTtl) + .build()); } public ConsulLockProvider( - @NonNull ConsulClient consulClient, - Duration minSessionTtl, - String consulLockPostfix, - Duration gracefulShutdownInterval) { + @NonNull ConsulClient consulClient, + Duration minSessionTtl, + String consulLockPostfix, + Duration gracefulShutdownInterval) { this(Configuration.builder() - .withConsulClient(consulClient) - .withMinSessionTtl(minSessionTtl) - .withConsulLockPostfix(consulLockPostfix) - .withGracefulShutdownInterval(gracefulShutdownInterval) - .build() - ); + .withConsulClient(consulClient) + .withMinSessionTtl(minSessionTtl) + .withConsulLockPostfix(consulLockPostfix) + .withGracefulShutdownInterval(gracefulShutdownInterval) + .build()); } public ConsulLockProvider(@NonNull Configuration configuration) { @@ -114,15 +115,17 @@ void unlock(String sessionId, LockConfiguration lockConfiguration) { } private String createSession(LockConfiguration lockConfiguration) { - long ttlInSeconds = Math.max(lockConfiguration.getLockAtMostFor().getSeconds(), - configuration.getMinSessionTtl().getSeconds()); + long ttlInSeconds = Math.max( + lockConfiguration.getLockAtMostFor().getSeconds(), + configuration.getMinSessionTtl().getSeconds()); NewSession newSession = new NewSession(); newSession.setName(lockConfiguration.getName()); newSession.setLockDelay(0); newSession.setBehavior(Session.Behavior.DELETE); newSession.setTtl(ttlInSeconds + "s"); - String sessionId = client().sessionCreate(newSession, QueryParams.DEFAULT, token()).getValue(); + String sessionId = + client().sessionCreate(newSession, QueryParams.DEFAULT, token()).getValue(); logger.debug("Acquired session {} for {} seconds", sessionId, ttlInSeconds); return sessionId; @@ -132,7 +135,8 @@ private Optional tryLock(String sessionId, LockConfiguration lockCon PutParams putParams = new PutParams(); putParams.setAcquireSession(sessionId); String leaderKey = getLeaderKey(lockConfiguration); - boolean isLockSuccessful = client().setKVValue(leaderKey, lockConfiguration.getName(), token(), putParams).getValue(); + boolean isLockSuccessful = client().setKVValue(leaderKey, lockConfiguration.getName(), token(), putParams) + .getValue(); if (isLockSuccessful) { return Optional.of(new ConsulSimpleLock(lockConfiguration, this, sessionId)); @@ -150,14 +154,13 @@ private String getLeaderKey(LockConfiguration lockConfiguration) { if (configuration.getConsulLockPrefix() == null) return lockConfiguration.getName() + configuration.getConsulLockPostfix(); - return configuration.getConsulLockPrefix() + "/" + lockConfiguration.getName() + configuration.getConsulLockPostfix(); + return configuration.getConsulLockPrefix() + "/" + lockConfiguration.getName() + + configuration.getConsulLockPostfix(); } private void scheduleUnlock(String sessionId, Duration unlockTime) { unlockScheduler.schedule( - catchExceptions(() -> destroy(sessionId)), - unlockTime.toMillis(), TimeUnit.MILLISECONDS - ); + catchExceptions(() -> destroy(sessionId)), unlockTime.toMillis(), TimeUnit.MILLISECONDS); } private void destroy(String sessionId) { @@ -179,8 +182,8 @@ private Runnable catchExceptions(Runnable runnable) { public void close() { unlockScheduler.shutdown(); try { - if (!unlockScheduler.awaitTermination(configuration.getGracefulShutdownInterval().toMillis(), - TimeUnit.MILLISECONDS)) { + if (!unlockScheduler.awaitTermination( + configuration.getGracefulShutdownInterval().toMillis(), TimeUnit.MILLISECONDS)) { unlockScheduler.shutdownNow(); } } catch (InterruptedException ignored) { @@ -199,15 +202,14 @@ public static final class Configuration { private final Duration gracefulShutdownInterval; private final String token; - /** - * Use Builder to create. - */ + /** Use Builder to create. */ Configuration( - Duration minSessionTtl, - String consulLockPostfix, - ConsulClient consulClient, - Duration gracefulShutdownInterval, - String token, String consulLockPrefix) { + Duration minSessionTtl, + String consulLockPostfix, + ConsulClient consulClient, + Duration gracefulShutdownInterval, + String token, + String consulLockPrefix) { this.minSessionTtl = minSessionTtl; this.consulLockPrefix = consulLockPrefix; @@ -286,9 +288,13 @@ public Builder withConsulLockPrefix(String leaderKeyPrefix) { public ConsulLockProvider.Configuration build() { return new ConsulLockProvider.Configuration( - minSessionTtl, consulLockPostfix, consulClient, gracefulShutdownInterval, token, consulLockPrefix); + minSessionTtl, + consulLockPostfix, + consulClient, + gracefulShutdownInterval, + token, + consulLockPrefix); } } } - } diff --git a/providers/consul/shedlock-provider-consul/src/main/java/net/javacrumbs/shedlock/provider/consul/ConsulSimpleLock.java b/providers/consul/shedlock-provider-consul/src/main/java/net/javacrumbs/shedlock/provider/consul/ConsulSimpleLock.java index a58da82c5..b4d615d30 100644 --- a/providers/consul/shedlock-provider-consul/src/main/java/net/javacrumbs/shedlock/provider/consul/ConsulSimpleLock.java +++ b/providers/consul/shedlock-provider-consul/src/main/java/net/javacrumbs/shedlock/provider/consul/ConsulSimpleLock.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.consul; @@ -22,9 +20,8 @@ class ConsulSimpleLock extends AbstractSimpleLock { private final ConsulLockProvider consulLockProvider; private final String sessionId; - public ConsulSimpleLock(LockConfiguration lockConfiguration, - ConsulLockProvider consulLockProvider, - String sessionId) { + public ConsulSimpleLock( + LockConfiguration lockConfiguration, ConsulLockProvider consulLockProvider, String sessionId) { super(lockConfiguration); this.consulLockProvider = consulLockProvider; this.sessionId = sessionId; diff --git a/providers/consul/shedlock-provider-consul/src/test/java/net/javacrumbs/shedlock/provider/consul/ConsulLockProviderIntegrationTest.java b/providers/consul/shedlock-provider-consul/src/test/java/net/javacrumbs/shedlock/provider/consul/ConsulLockProviderIntegrationTest.java index 45508db86..79d04f5d7 100644 --- a/providers/consul/shedlock-provider-consul/src/test/java/net/javacrumbs/shedlock/provider/consul/ConsulLockProviderIntegrationTest.java +++ b/providers/consul/shedlock-provider-consul/src/test/java/net/javacrumbs/shedlock/provider/consul/ConsulLockProviderIntegrationTest.java @@ -1,25 +1,29 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.consul; +import static java.lang.Thread.sleep; +import static org.assertj.core.api.Assertions.assertThat; + import com.ecwid.consul.v1.ConsulClient; import com.ecwid.consul.v1.QueryParams; import com.ecwid.consul.v1.Response; import com.ecwid.consul.v1.kv.model.GetValue; import com.ecwid.consul.v1.session.model.Session; +import java.time.Duration; +import java.util.List; +import java.util.Optional; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.SimpleLock; @@ -32,13 +36,6 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import java.time.Duration; -import java.util.List; -import java.util.Optional; - -import static java.lang.Thread.sleep; -import static org.assertj.core.api.Assertions.assertThat; - @Testcontainers class ConsulLockProviderIntegrationTest extends AbstractLockProviderIntegrationTest { @@ -56,16 +53,15 @@ public static void startConsul() { public void checkSessions() { Response> sessionListResponse = consulClient.getSessionList(QueryParams.DEFAULT); assertThat(sessionListResponse.getValue()) - .as("There should no sessions remain in consul after all locks have been released.") - .isEmpty(); + .as("There should no sessions remain in consul after all locks have been released.") + .isEmpty(); } @Override protected LockProvider getLockProvider() { - return new ConsulLockProvider( - ConsulLockProvider.Configuration.builder() - .withConsulClient(consulClient).build() - ); + return new ConsulLockProvider(ConsulLockProvider.Configuration.builder() + .withConsulClient(consulClient) + .build()); } @Override @@ -87,7 +83,9 @@ private GetValue getLockValue(String lockName) { @Test @Override public void shouldTimeout() throws InterruptedException { - // as consul has 10 seconds ttl minimum and has double ttl unlocking time, you have to wait for 20 seconds for the unlock time. + // as consul has 10 seconds ttl minimum and has double ttl unlocking time, you + // have to wait for + // 20 seconds for the unlock time. Duration lockAtMostFor = Duration.ofSeconds(11); LockConfiguration configWithShortTimeout = lockConfig(LOCK_NAME1, lockAtMostFor, Duration.ZERO); Optional lock1 = getLockProvider().lock(configWithShortTimeout); @@ -96,7 +94,8 @@ public void shouldTimeout() throws InterruptedException { sleep(lockAtMostFor.multipliedBy(2).toMillis() + 100); assertUnlocked(LOCK_NAME1); - Optional lock2 = getLockProvider().lock(lockConfig(LOCK_NAME1, Duration.ofMillis(50), Duration.ZERO)); + Optional lock2 = + getLockProvider().lock(lockConfig(LOCK_NAME1, Duration.ofMillis(50), Duration.ZERO)); assertThat(lock2).isNotEmpty(); lock2.get().unlock(); } @@ -119,18 +118,9 @@ private static class MyConsulContainer extends GenericContainerLicensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.consul; -import com.ecwid.consul.v1.ConsulClient; -import com.ecwid.consul.v1.QueryParams; -import com.ecwid.consul.v1.Response; -import com.ecwid.consul.v1.kv.model.PutParams; -import net.javacrumbs.shedlock.core.ClockProvider; -import net.javacrumbs.shedlock.core.LockConfiguration; -import net.javacrumbs.shedlock.core.SimpleLock; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.time.Duration; -import java.util.Optional; -import java.util.UUID; - import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.anyString; @@ -39,15 +23,31 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.ecwid.consul.v1.ConsulClient; +import com.ecwid.consul.v1.QueryParams; +import com.ecwid.consul.v1.Response; +import com.ecwid.consul.v1.kv.model.PutParams; +import java.time.Duration; +import java.util.Optional; +import java.util.UUID; +import net.javacrumbs.shedlock.core.ClockProvider; +import net.javacrumbs.shedlock.core.LockConfiguration; +import net.javacrumbs.shedlock.core.SimpleLock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + class ConsulLockProviderTest { - // lower values may produce false negatives because scheduler may not complete necessary tasks in time + // lower values may produce false negatives because scheduler may not complete + // necessary tasks in + // time private static final Duration SMALL_MIN_TTL = Duration.ofMillis(200); private final ConsulClient mockConsulClient = mock(ConsulClient.class); private final ConsulLockProvider lockProvider = new ConsulLockProvider(mockConsulClient, SMALL_MIN_TTL); @BeforeEach void setUp() { - when(mockConsulClient.sessionCreate(any(), any(), any())).thenReturn(new Response<>(UUID.randomUUID().toString(), null, null, null)); + when(mockConsulClient.sessionCreate(any(), any(), any())) + .thenReturn(new Response<>(UUID.randomUUID().toString(), null, null, null)); mockLock(any(), true); } @@ -90,15 +90,18 @@ void destroysSessionIfLockIsAlreadyObtained() { @Test void doesNotBlockSchedulerInCaseOfFailure() { when(mockConsulClient.sessionDestroy(any(), any(), any())) - .thenThrow(new RuntimeException("Sasuke is not in Konoha, Naruto alone is unable to destroy session :(")) - .thenReturn(new Response<>(null, null, null, null)); + .thenThrow( + new RuntimeException("Sasuke is not in Konoha, Naruto alone is unable to destroy session :(")) + .thenReturn(new Response<>(null, null, null, null)); - Optional lock = lockProvider.lock(lockConfig("sasuke", SMALL_MIN_TTL.multipliedBy(10), SMALL_MIN_TTL)); + Optional lock = + lockProvider.lock(lockConfig("sasuke", SMALL_MIN_TTL.multipliedBy(10), SMALL_MIN_TTL)); assertThat(lock).isNotEmpty(); lock.get().unlock(); sleep(SMALL_MIN_TTL.toMillis() + 10); - Optional lock2 = lockProvider.lock(lockConfig("sakura", SMALL_MIN_TTL.multipliedBy(10), SMALL_MIN_TTL)); + Optional lock2 = + lockProvider.lock(lockConfig("sakura", SMALL_MIN_TTL.multipliedBy(10), SMALL_MIN_TTL)); assertThat(lock2).isNotEmpty(); lock2.get().unlock(); sleep(SMALL_MIN_TTL.toMillis() + 10); @@ -108,7 +111,7 @@ void doesNotBlockSchedulerInCaseOfFailure() { private void mockLock(String eq, boolean b) { when(mockConsulClient.setKVValue(eq, any(), any(), any(PutParams.class))) - .thenReturn(new Response<>(b, null, null, null)); + .thenReturn(new Response<>(b, null, null, null)); } private LockConfiguration lockConfig(String name, Duration lockAtMostFor, Duration lockAtLeastFor) { diff --git a/providers/couchbase/shedlock-provider-couchbase-javaclient3/src/main/java/net/javacrumbs/shedlock/provider/couchbase/javaclient3/CouchbaseLockProvider.java b/providers/couchbase/shedlock-provider-couchbase-javaclient3/src/main/java/net/javacrumbs/shedlock/provider/couchbase/javaclient3/CouchbaseLockProvider.java index 4e04a3f49..39b0d3a0f 100644 --- a/providers/couchbase/shedlock-provider-couchbase-javaclient3/src/main/java/net/javacrumbs/shedlock/provider/couchbase/javaclient3/CouchbaseLockProvider.java +++ b/providers/couchbase/shedlock-provider-couchbase-javaclient3/src/main/java/net/javacrumbs/shedlock/provider/couchbase/javaclient3/CouchbaseLockProvider.java @@ -1,20 +1,20 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.couchbase.javaclient3; +import static net.javacrumbs.shedlock.support.Utils.toIsoString; + import com.couchbase.client.core.error.CasMismatchException; import com.couchbase.client.core.error.DocumentExistsException; import com.couchbase.client.java.Bucket; @@ -22,20 +22,19 @@ import com.couchbase.client.java.json.JsonObject; import com.couchbase.client.java.kv.GetResult; import com.couchbase.client.java.kv.ReplaceOptions; +import java.time.Instant; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.support.AbstractStorageAccessor; import net.javacrumbs.shedlock.support.StorageBasedLockProvider; import net.javacrumbs.shedlock.support.annotation.NonNull; -import java.time.Instant; - -import static net.javacrumbs.shedlock.support.Utils.toIsoString; - /** * Distributed lock using CouchbaseDB + * *

* It uses a collection that contains documents like this: + * *

  * {
  *    "_id" : "lock name",
@@ -45,24 +44,21 @@
  * }
  * 
* - * lockedAt and lockedBy are just for troubleshooting and are not read by the code + * lockedAt and lockedBy are just for troubleshooting and are not read by the + * code * *
    - *
  1. - * Attempts to insert a new lock record. As an optimization, we keep in-memory track of created lock records. If the record - * has been inserted, returns lock. - *
  2. - *
  3. - * We will try to update lock record using filter _id == name AND lock_until <= now - *
  4. - *
  5. - * If the update succeeded (1 updated document), we have the lock. If the update failed (0 updated documents) somebody else holds the lock - * Obtaining a optimistic lock in Couchbase Server, Uses the check-and-set (CAS) API to retrieve a CAS revision number - * CAS number prevents from 2 users to update the same document at the same time. - *
  6. - *
  7. - * When unlocking, lock_until is set to now. - *
  8. + *
  9. Attempts to insert a new lock record. As an optimization, we keep + * in-memory track of created lock records. If the record has been inserted, + * returns lock. + *
  10. We will try to update lock record using filter _id == name AND lock_until + * <= now + *
  11. If the update succeeded (1 updated document), we have the lock. If the + * update failed (0 updated documents) somebody else holds the lock Obtaining a + * optimistic lock in Couchbase Server, Uses the check-and-set (CAS) API to + * retrieve a CAS revision number CAS number prevents from 2 users to update the + * same document at the same time. + *
  12. When unlocking, lock_until is set to now. *
*/ public class CouchbaseLockProvider extends StorageBasedLockProvider { @@ -94,10 +90,10 @@ private static class CouchbaseAccessor extends AbstractStorageAccessor { @Override public boolean insertRecord(@NonNull LockConfiguration lockConfiguration) { JsonObject content = JsonObject.create() - .put(LOCK_NAME, lockConfiguration.getName()) - .put(LOCK_UNTIL, toIsoString(lockConfiguration.getLockAtMostUntil())) - .put(LOCKED_AT, toIsoString(ClockProvider.now())) - .put(LOCKED_BY, getHostname()); + .put(LOCK_NAME, lockConfiguration.getName()) + .put(LOCK_UNTIL, toIsoString(lockConfiguration.getLockAtMostUntil())) + .put(LOCKED_AT, toIsoString(ClockProvider.now())) + .put(LOCKED_BY, getHostname()); try { collection.insert(lockConfiguration.getName(), content); @@ -127,8 +123,10 @@ public boolean updateRecord(@NonNull LockConfiguration lockConfiguration) { document.put(LOCKED_BY, getHostname()); try { - collection.replace(lockConfiguration.getName(), document, - ReplaceOptions.replaceOptions().cas(result.cas())); + collection.replace( + lockConfiguration.getName(), + document, + ReplaceOptions.replaceOptions().cas(result.cas())); } catch (CasMismatchException e) { return false; } @@ -149,8 +147,10 @@ public boolean extend(@NonNull LockConfiguration lockConfiguration) { document.put(LOCK_UNTIL, toIsoString(lockConfiguration.getLockAtMostUntil())); try { - collection.replace(lockConfiguration.getName(), document, - ReplaceOptions.replaceOptions().cas(result.cas())); + collection.replace( + lockConfiguration.getName(), + document, + ReplaceOptions.replaceOptions().cas(result.cas())); } catch (CasMismatchException e) { return false; } @@ -166,6 +166,4 @@ public void unlock(@NonNull LockConfiguration lockConfiguration) { collection.replace(lockConfiguration.getName(), document); } } - } - diff --git a/providers/couchbase/shedlock-provider-couchbase-javaclient3/src/test/java/net/javacrumbs/shedlock/provider/couchbase/javaclient3/CouchbaseLockProviderIntegrationTest.java b/providers/couchbase/shedlock-provider-couchbase-javaclient3/src/test/java/net/javacrumbs/shedlock/provider/couchbase/javaclient3/CouchbaseLockProviderIntegrationTest.java index 9a3f7333f..4db500a90 100644 --- a/providers/couchbase/shedlock-provider-couchbase-javaclient3/src/test/java/net/javacrumbs/shedlock/provider/couchbase/javaclient3/CouchbaseLockProviderIntegrationTest.java +++ b/providers/couchbase/shedlock-provider-couchbase-javaclient3/src/test/java/net/javacrumbs/shedlock/provider/couchbase/javaclient3/CouchbaseLockProviderIntegrationTest.java @@ -1,20 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.couchbase.javaclient3; +import static java.time.Instant.parse; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static net.javacrumbs.shedlock.provider.couchbase.javaclient3.CouchbaseLockProvider.LOCKED_AT; +import static net.javacrumbs.shedlock.provider.couchbase.javaclient3.CouchbaseLockProvider.LOCKED_BY; +import static net.javacrumbs.shedlock.provider.couchbase.javaclient3.CouchbaseLockProvider.LOCK_UNTIL; +import static org.assertj.core.api.Assertions.assertThat; + import com.couchbase.client.core.env.SeedNode; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; @@ -22,6 +27,11 @@ import com.couchbase.client.java.Collection; import com.couchbase.client.java.json.JsonObject; import com.couchbase.client.java.kv.GetResult; +import java.time.Duration; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; import net.javacrumbs.shedlock.support.StorageBasedLockProvider; import net.javacrumbs.shedlock.test.support.AbstractStorageBasedLockProviderIntegrationTest; import org.junit.jupiter.api.AfterAll; @@ -31,20 +41,6 @@ import org.testcontainers.couchbase.BucketDefinition; import org.testcontainers.couchbase.CouchbaseContainer; -import java.time.Duration; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import static java.time.Instant.parse; -import static java.util.Collections.singletonList; -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static net.javacrumbs.shedlock.provider.couchbase.javaclient3.CouchbaseLockProvider.LOCKED_AT; -import static net.javacrumbs.shedlock.provider.couchbase.javaclient3.CouchbaseLockProvider.LOCKED_BY; -import static net.javacrumbs.shedlock.provider.couchbase.javaclient3.CouchbaseLockProvider.LOCK_UNTIL; -import static org.assertj.core.api.Assertions.assertThat; - public class CouchbaseLockProviderIntegrationTest extends AbstractStorageBasedLockProviderIntegrationTest { private static final String BUCKET_NAME = "test"; @@ -56,12 +52,12 @@ public class CouchbaseLockProviderIntegrationTest extends AbstractStorageBasedLo private static CouchbaseContainer container; @BeforeAll - public static void startCouchbase () { + public static void startCouchbase() { container = new CouchbaseContainer().withBucket(new BucketDefinition(BUCKET_NAME)); container.start(); - Set seedNodes = new HashSet<>(List.of( - SeedNode.create(container.getContainerIpAddress(), + Set seedNodes = new HashSet<>(List.of(SeedNode.create( + container.getContainerIpAddress(), Optional.of(container.getBootstrapCarrierDirectPort()), Optional.of(container.getBootstrapHttpDirectPort())))); ClusterOptions options = ClusterOptions.clusterOptions(container.getUsername(), container.getPassword()); @@ -73,13 +69,13 @@ public static void startCouchbase () { } @AfterAll - public static void stopCouchbase () { + public static void stopCouchbase() { cluster.disconnect(); container.stop(); } @BeforeEach - public void createLockProvider() { + public void createLockProvider() { lockProvider = new CouchbaseLockProvider(bucket.defaultCollection()); } diff --git a/providers/datastore/shedlock-provider-datastore/src/main/java/net/javacrumbs/shedlock/provider/datastore/DatastoreLockProvider.java b/providers/datastore/shedlock-provider-datastore/src/main/java/net/javacrumbs/shedlock/provider/datastore/DatastoreLockProvider.java index 569d59be0..3813dea16 100644 --- a/providers/datastore/shedlock-provider-datastore/src/main/java/net/javacrumbs/shedlock/provider/datastore/DatastoreLockProvider.java +++ b/providers/datastore/shedlock-provider-datastore/src/main/java/net/javacrumbs/shedlock/provider/datastore/DatastoreLockProvider.java @@ -1,14 +1,15 @@ package net.javacrumbs.shedlock.provider.datastore; +import static java.util.Objects.requireNonNull; + import com.google.cloud.datastore.Datastore; import net.javacrumbs.shedlock.support.StorageBasedLockProvider; -import static java.util.Objects.requireNonNull; - public class DatastoreLockProvider extends StorageBasedLockProvider { public DatastoreLockProvider(Datastore datastore) { - super(new DatastoreStorageAccessor(Configuration.builder().withDatastore(datastore).build())); + super(new DatastoreStorageAccessor( + Configuration.builder().withDatastore(datastore).build())); } public DatastoreLockProvider(Configuration configuration) { diff --git a/providers/datastore/shedlock-provider-datastore/src/main/java/net/javacrumbs/shedlock/provider/datastore/DatastoreStorageAccessor.java b/providers/datastore/shedlock-provider-datastore/src/main/java/net/javacrumbs/shedlock/provider/datastore/DatastoreStorageAccessor.java index dd0edcc18..96cafbdd5 100644 --- a/providers/datastore/shedlock-provider-datastore/src/main/java/net/javacrumbs/shedlock/provider/datastore/DatastoreStorageAccessor.java +++ b/providers/datastore/shedlock-provider-datastore/src/main/java/net/javacrumbs/shedlock/provider/datastore/DatastoreStorageAccessor.java @@ -1,5 +1,8 @@ package net.javacrumbs.shedlock.provider.datastore; +import static java.util.Objects.requireNonNull; +import static java.util.Optional.ofNullable; + import com.google.cloud.Timestamp; import com.google.cloud.datastore.Datastore; import com.google.cloud.datastore.DatastoreException; @@ -7,6 +10,9 @@ import com.google.cloud.datastore.Key; import com.google.cloud.datastore.KeyFactory; import com.google.cloud.datastore.Transaction; +import java.time.Instant; +import java.util.Optional; +import java.util.function.Function; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.support.AbstractStorageAccessor; @@ -14,13 +20,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Instant; -import java.util.Optional; -import java.util.function.Function; - -import static java.util.Objects.requireNonNull; -import static java.util.Optional.ofNullable; - public class DatastoreStorageAccessor extends AbstractStorageAccessor { private static final Logger log = LoggerFactory.getLogger(DatastoreStorageAccessor.class); @@ -59,63 +58,61 @@ public boolean extend(LockConfiguration config) { private boolean insert(String name, Instant until) { return doInTxn(txn -> { - KeyFactory keyFactory = this.datastore.newKeyFactory().setKind(this.entityName); - Key key = keyFactory.newKey(name); - Entity entity = Entity.newBuilder(key) - .set(this.fieldNames.lockUntil(), fromInstant(until)) - .set(this.fieldNames.lockedAt(), fromInstant(ClockProvider.now())) - .set(this.fieldNames.lockedBy(), this.hostname) - .build(); - txn.add(entity); - return Optional.of(true); - }).orElse(false); + KeyFactory keyFactory = this.datastore.newKeyFactory().setKind(this.entityName); + Key key = keyFactory.newKey(name); + Entity entity = Entity.newBuilder(key) + .set(this.fieldNames.lockUntil(), fromInstant(until)) + .set(this.fieldNames.lockedAt(), fromInstant(ClockProvider.now())) + .set(this.fieldNames.lockedBy(), this.hostname) + .build(); + txn.add(entity); + return Optional.of(true); + }) + .orElse(false); } private boolean updateExisting(String name, Instant until) { - return doInTxn(txn -> - get(name, txn) - .filter(entity -> { - var now = ClockProvider.now(); - var lockUntilTs = nullableTimestamp(entity, this.fieldNames.lockUntil()); - return lockUntilTs != null && lockUntilTs.isBefore(now); - }) - .map(entity -> { - txn.put(Entity.newBuilder(entity) - .set(this.fieldNames.lockUntil(), fromInstant(until)) - .set(this.fieldNames.lockedAt(), fromInstant(ClockProvider.now())) - .set(this.fieldNames.lockedBy(), this.hostname) - .build()); - return true; - }) - ).orElse(false); + return doInTxn(txn -> get(name, txn) + .filter(entity -> { + var now = ClockProvider.now(); + var lockUntilTs = nullableTimestamp(entity, this.fieldNames.lockUntil()); + return lockUntilTs != null && lockUntilTs.isBefore(now); + }) + .map(entity -> { + txn.put(Entity.newBuilder(entity) + .set(this.fieldNames.lockUntil(), fromInstant(until)) + .set(this.fieldNames.lockedAt(), fromInstant(ClockProvider.now())) + .set(this.fieldNames.lockedBy(), this.hostname) + .build()); + return true; + })) + .orElse(false); } private boolean updateOwn(String name, Instant until) { - return doInTxn(txn -> - get(name, txn) - .filter(entity -> this.hostname.equals(nullableString(entity, this.fieldNames.lockedBy()))) - .filter(entity -> { - var now = ClockProvider.now(); - var lockUntilTs = nullableTimestamp(entity, this.fieldNames.lockUntil()); - return lockUntilTs != null && (lockUntilTs.isAfter(now) || lockUntilTs.equals(now)); - }) - .map(entity -> { - txn.put(Entity.newBuilder(entity) - .set(this.fieldNames.lockUntil(), fromInstant(until)) - .build()); - return true; - }) - ).orElse(false); + return doInTxn(txn -> get(name, txn) + .filter(entity -> this.hostname.equals(nullableString(entity, this.fieldNames.lockedBy()))) + .filter(entity -> { + var now = ClockProvider.now(); + var lockUntilTs = nullableTimestamp(entity, this.fieldNames.lockUntil()); + return lockUntilTs != null && (lockUntilTs.isAfter(now) || lockUntilTs.equals(now)); + }) + .map(entity -> { + txn.put(Entity.newBuilder(entity) + .set(this.fieldNames.lockUntil(), fromInstant(until)) + .build()); + return true; + })) + .orElse(false); } public Optional findLock(String name) { return get(name) - .map(entity -> new Lock( - entity.getKey().getName(), - nullableTimestamp(entity, this.fieldNames.lockedAt()), - nullableTimestamp(entity, this.fieldNames.lockUntil()), - nullableString(entity, this.fieldNames.lockedBy()) - )); + .map(entity -> new Lock( + entity.getKey().getName(), + nullableTimestamp(entity, this.fieldNames.lockedAt()), + nullableTimestamp(entity, this.fieldNames.lockUntil()), + nullableString(entity, this.fieldNames.lockedBy()))); } private Optional get(String name) { @@ -162,6 +159,5 @@ private static Instant toInstant(Timestamp timestamp) { return requireNonNull(timestamp).toSqlTimestamp().toInstant(); } - public record Lock(String name, Instant lockedAt, Instant lockedUntil, String lockedBy) { - } + public record Lock(String name, Instant lockedAt, Instant lockedUntil, String lockedBy) {} } diff --git a/providers/datastore/shedlock-provider-datastore/src/test/java/net/javacrumbs/shedlock/provider/datastore/DatastoreLockProviderIntegrationTest.java b/providers/datastore/shedlock-provider-datastore/src/test/java/net/javacrumbs/shedlock/provider/datastore/DatastoreLockProviderIntegrationTest.java index 418278dfd..ba8f8e9fa 100644 --- a/providers/datastore/shedlock-provider-datastore/src/test/java/net/javacrumbs/shedlock/provider/datastore/DatastoreLockProviderIntegrationTest.java +++ b/providers/datastore/shedlock-provider-datastore/src/test/java/net/javacrumbs/shedlock/provider/datastore/DatastoreLockProviderIntegrationTest.java @@ -1,9 +1,13 @@ package net.javacrumbs.shedlock.provider.datastore; +import static com.google.cloud.datastore.Query.ResultType.ENTITY; +import static org.assertj.core.api.Assertions.assertThat; + import com.google.cloud.NoCredentials; import com.google.cloud.datastore.Datastore; import com.google.cloud.datastore.DatastoreOptions; import com.google.cloud.datastore.Query; +import java.util.Optional; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.support.StorageBasedLockProvider; import net.javacrumbs.shedlock.test.support.AbstractStorageBasedLockProviderIntegrationTest; @@ -14,20 +18,18 @@ import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; -import java.util.Optional; - -import static com.google.cloud.datastore.Query.ResultType.ENTITY; -import static org.assertj.core.api.Assertions.assertThat; - @Testcontainers class DatastoreLockProviderIntegrationTest extends AbstractStorageBasedLockProviderIntegrationTest { @Container public static final DatastoreEmulatorContainer datastoreEmulator; + static { - DockerImageName googleCloudCliImage = DockerImageName.parse("gcr.io/google.com/cloudsdktool/google-cloud-cli:425.0.0-emulators"); + DockerImageName googleCloudCliImage = + DockerImageName.parse("gcr.io/google.com/cloudsdktool/google-cloud-cli:425.0.0-emulators"); datastoreEmulator = new DatastoreEmulatorContainer(googleCloudCliImage) - .withFlags("--project shedlock-provider-datastore-test --host-port 0.0.0.0:8081 --use-firestore-in-datastore-mode") - .withReuse(true); + .withFlags( + "--project shedlock-provider-datastore-test --host-port 0.0.0.0:8081 --use-firestore-in-datastore-mode") + .withReuse(true); } private Datastore datastore; @@ -38,16 +40,16 @@ class DatastoreLockProviderIntegrationTest extends AbstractStorageBasedLockProvi @BeforeEach void init() { this.datastore = DatastoreOptions.newBuilder() - .setCredentials(NoCredentials.getInstance()) - .setProjectId("shedlock-provider-datastore-test") - .setHost("http://" + datastoreEmulator.getEmulatorEndpoint()) - .build() - .getService(); + .setCredentials(NoCredentials.getInstance()) + .setProjectId("shedlock-provider-datastore-test") + .setHost("http://" + datastoreEmulator.getEmulatorEndpoint()) + .build() + .getService(); this.configuration = DatastoreLockProvider.Configuration.builder() - .withDatastore(datastore) - .withEntityName("shedlock") - .withFieldNames(new DatastoreLockProvider.FieldNames("until", "at", "by")) - .build(); + .withDatastore(datastore) + .withEntityName("shedlock") + .withFieldNames(new DatastoreLockProvider.FieldNames("until", "at", "by")) + .build(); this.accessor = new DatastoreStorageAccessor(this.configuration); this.provider = new DatastoreLockProvider(this.configuration); } diff --git a/providers/dynamodb/shedlock-provider-dynamodb2/src/main/java/net/javacrumbs/shedlock/provider/dynamodb2/DynamoDBLockProvider.java b/providers/dynamodb/shedlock-provider-dynamodb2/src/main/java/net/javacrumbs/shedlock/provider/dynamodb2/DynamoDBLockProvider.java index ea49af51e..867f30ca6 100644 --- a/providers/dynamodb/shedlock-provider-dynamodb2/src/main/java/net/javacrumbs/shedlock/provider/dynamodb2/DynamoDBLockProvider.java +++ b/providers/dynamodb/shedlock-provider-dynamodb2/src/main/java/net/javacrumbs/shedlock/provider/dynamodb2/DynamoDBLockProvider.java @@ -1,20 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.dynamodb2; +import static java.util.Collections.singletonMap; +import static java.util.Objects.requireNonNull; +import static net.javacrumbs.shedlock.support.Utils.toIsoString; + +import java.time.Instant; +import java.util.Map; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; @@ -28,19 +33,13 @@ import software.amazon.awssdk.services.dynamodb.model.ReturnValue; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; -import java.time.Instant; -import java.util.Map; -import java.util.Optional; - -import static java.util.Collections.singletonMap; -import static java.util.Objects.requireNonNull; -import static net.javacrumbs.shedlock.support.Utils.toIsoString; - /** - * Distributed lock using DynamoDB. - * Depends on software.amazon.awssdk:dynamodb. + * Distributed lock using DynamoDB. Depends on + * software.amazon.awssdk:dynamodb. + * *

* It uses a table with the following structure: + * *

  * {
  *    "_id" : "lock name",
@@ -54,19 +53,14 @@
  * and are not read by the code.
  *
  * 
    - *
  1. - * Attempts to insert a new lock record. - *
  2. - *
  3. - * We will try to update lock record using filter _id == :name AND lock_until <= :now. - *
  4. - *
  5. - * If the update succeeded, we have the lock. If the update failed (condition check exception) - * somebody else holds the lock. - *
  6. - *
  7. - * When unlocking, lock_until is set to now or lockAtLeastUntil whichever is later. - *
  8. + *
  9. Attempts to insert a new lock record. + *
  10. We will try to update lock record using + * filter _id == :name AND lock_until <= :now + * . + *
  11. If the update succeeded, we have the lock. If the update failed + * (condition check exception) somebody else holds the lock. + *
  12. When unlocking, lock_until is set to now or + * lockAtLeastUntil whichever is later. *
*/ public class DynamoDBLockProvider implements LockProvider { @@ -79,8 +73,7 @@ public class DynamoDBLockProvider implements LockProvider { "set " + LOCK_UNTIL + " = :lockUntil, " + LOCKED_AT + " = :lockedAt, " + LOCKED_BY + " = :lockedBy"; private static final String OBTAIN_LOCK_CONDITION = LOCK_UNTIL + " <= :lockedAt or attribute_not_exists(" + LOCK_UNTIL + ")"; - private static final String RELEASE_LOCK_QUERY = - "set " + LOCK_UNTIL + " = :lockUntil"; + private static final String RELEASE_LOCK_QUERY = "set " + LOCK_UNTIL + " = :lockUntil"; private final String hostname; private final DynamoDbClient dynamoDbClient; @@ -89,8 +82,10 @@ public class DynamoDBLockProvider implements LockProvider { /** * Uses DynamoDB to coordinate locks * - * @param dynamoDbClient v2 of DynamoDB client - * @param tableName the lock table name + * @param dynamoDbClient + * v2 of DynamoDB client + * @param tableName + * the lock table name */ public DynamoDBLockProvider(@NonNull DynamoDbClient dynamoDbClient, @NonNull String tableName) { this.dynamoDbClient = requireNonNull(dynamoDbClient, "dynamoDbClient can not be null"); @@ -106,11 +101,8 @@ public Optional lock(@NonNull LockConfiguration lockConfiguration) { Map key = singletonMap(ID, attr(lockConfiguration.getName())); - Map attributeUpdates = Map.of( - ":lockUntil", attr(lockUntilIso), - ":lockedAt", attr(nowIso), - ":lockedBy", attr(hostname) - ); + Map attributeUpdates = + Map.of(":lockUntil", attr(lockUntilIso), ":lockedAt", attr(nowIso), ":lockedBy", attr(hostname)); UpdateItemRequest request = UpdateItemRequest.builder() .tableName(tableName) @@ -124,8 +116,10 @@ public Optional lock(@NonNull LockConfiguration lockConfiguration) { try { // There are three possible situations: // 1. The lock document does not exist yet - it is inserted - we have the lock - // 2. The lock document exists and lockUtil <= now - it is updated - we have the lock - // 3. The lock document exists and lockUtil > now - ConditionalCheckFailedException is thrown + // 2. The lock document exists and lockUtil <= now - it is updated - we have the + // lock + // 3. The lock document exists and lockUtil > now - + // ConditionalCheckFailedException is thrown dynamoDbClient.updateItem(request); return Optional.of(new DynamoDBLock(dynamoDbClient, tableName, lockConfiguration)); } catch (ConditionalCheckFailedException e) { @@ -135,9 +129,7 @@ public Optional lock(@NonNull LockConfiguration lockConfiguration) { } private static AttributeValue attr(String lockUntilIso) { - return AttributeValue.builder() - .s(lockUntilIso) - .build(); + return AttributeValue.builder().s(lockUntilIso).build(); } private Instant now() { @@ -148,11 +140,7 @@ private static final class DynamoDBLock extends AbstractSimpleLock { private final DynamoDbClient dynamoDbClient; private final String tableName; - private DynamoDBLock( - DynamoDbClient dynamoDbClient, - String tableName, - LockConfiguration lockConfiguration - ) { + private DynamoDBLock(DynamoDbClient dynamoDbClient, String tableName, LockConfiguration lockConfiguration) { super(lockConfiguration); this.dynamoDbClient = dynamoDbClient; this.tableName = tableName; diff --git a/providers/dynamodb/shedlock-provider-dynamodb2/src/main/java/net/javacrumbs/shedlock/provider/dynamodb2/DynamoDBUtils.java b/providers/dynamodb/shedlock-provider-dynamodb2/src/main/java/net/javacrumbs/shedlock/provider/dynamodb2/DynamoDBUtils.java index bd56433bc..1ca5c15f3 100644 --- a/providers/dynamodb/shedlock-provider-dynamodb2/src/main/java/net/javacrumbs/shedlock/provider/dynamodb2/DynamoDBUtils.java +++ b/providers/dynamodb/shedlock-provider-dynamodb2/src/main/java/net/javacrumbs/shedlock/provider/dynamodb2/DynamoDBUtils.java @@ -1,20 +1,20 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.dynamodb2; +import static net.javacrumbs.shedlock.provider.dynamodb2.DynamoDBLockProvider.ID; + import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; @@ -24,29 +24,27 @@ import software.amazon.awssdk.services.dynamodb.model.ResourceInUseException; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; -import static net.javacrumbs.shedlock.provider.dynamodb2.DynamoDBLockProvider.ID; - public class DynamoDBUtils { /** * Creates a locking table with the given name. + * *

* This method does not check if a table with the given name exists already. * - * @param ddbClient v2 of DynamoDBClient - * @param tableName table to be used - * @param throughput AWS {@link ProvisionedThroughput throughput requirements} for the given lock setup - * @return the table name - * + * @param ddbClient + * v2 of DynamoDBClient + * @param tableName + * table to be used + * @param throughput + * AWS {@link ProvisionedThroughput throughput requirements} for the + * given lock setup + * @return the table name * @throws ResourceInUseException - * The operation conflicts with the resource's availability. You attempted to recreate an - * existing table. + * The operation conflicts with the resource's availability. You + * attempted to recreate an existing table. */ - public static String createLockTable( - DynamoDbClient ddbClient, - String tableName, - ProvisionedThroughput throughput - ) { + public static String createLockTable(DynamoDbClient ddbClient, String tableName, ProvisionedThroughput throughput) { CreateTableRequest request = CreateTableRequest.builder() .tableName(tableName) diff --git a/providers/dynamodb/shedlock-provider-dynamodb2/src/test/java/net/javacrumbs/shedlock/provider/dynamodb2/DynamoDBLockProviderIntegrationTest.java b/providers/dynamodb/shedlock-provider-dynamodb2/src/test/java/net/javacrumbs/shedlock/provider/dynamodb2/DynamoDBLockProviderIntegrationTest.java index ce91ff389..a7d904446 100644 --- a/providers/dynamodb/shedlock-provider-dynamodb2/src/test/java/net/javacrumbs/shedlock/provider/dynamodb2/DynamoDBLockProviderIntegrationTest.java +++ b/providers/dynamodb/shedlock-provider-dynamodb2/src/test/java/net/javacrumbs/shedlock/provider/dynamodb2/DynamoDBLockProviderIntegrationTest.java @@ -1,20 +1,29 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.dynamodb2; +import static net.javacrumbs.shedlock.provider.dynamodb2.DynamoDBLockProvider.ID; +import static net.javacrumbs.shedlock.provider.dynamodb2.DynamoDBLockProvider.LOCKED_AT; +import static net.javacrumbs.shedlock.provider.dynamodb2.DynamoDBLockProvider.LOCKED_BY; +import static net.javacrumbs.shedlock.provider.dynamodb2.DynamoDBLockProvider.LOCK_UNTIL; +import static org.assertj.core.api.Assertions.assertThat; + +import java.net.URI; +import java.time.Instant; +import java.util.Collections; +import java.util.List; +import java.util.Map; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.test.support.AbstractLockProviderIntegrationTest; import org.junit.jupiter.api.AfterEach; @@ -35,25 +44,11 @@ import software.amazon.awssdk.services.dynamodb.model.ScanRequest; import software.amazon.awssdk.services.dynamodb.model.TableStatus; -import java.net.URI; -import java.time.Instant; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import static net.javacrumbs.shedlock.provider.dynamodb2.DynamoDBLockProvider.ID; -import static net.javacrumbs.shedlock.provider.dynamodb2.DynamoDBLockProvider.LOCKED_AT; -import static net.javacrumbs.shedlock.provider.dynamodb2.DynamoDBLockProvider.LOCKED_BY; -import static net.javacrumbs.shedlock.provider.dynamodb2.DynamoDBLockProvider.LOCK_UNTIL; -import static org.assertj.core.api.Assertions.assertThat; - @Testcontainers public class DynamoDBLockProviderIntegrationTest extends AbstractLockProviderIntegrationTest { @Container public static final DynamoDbContainer dynamoDbContainer = - new DynamoDbContainer("quay.io/testcontainers/dynalite:v1.2.1-1") - .withExposedPorts(4567); - + new DynamoDbContainer("quay.io/testcontainers/dynalite:v1.2.1-1").withExposedPorts(4567); private static final String TABLE_NAME = "Shedlock"; private static DynamoDbClient dynamodb; @@ -62,18 +57,21 @@ public class DynamoDBLockProviderIntegrationTest extends AbstractLockProviderInt static void createLockProvider() { dynamodb = createClient(); String lockTable = DynamoDBUtils.createLockTable( - dynamodb, - TABLE_NAME, - ProvisionedThroughput.builder() - .readCapacityUnits(1L) - .writeCapacityUnits(1L) - .build() - ); - while (getTableStatus(lockTable) != TableStatus.ACTIVE) ; + dynamodb, + TABLE_NAME, + ProvisionedThroughput.builder() + .readCapacityUnits(1L) + .writeCapacityUnits(1L) + .build()); + while (getTableStatus(lockTable) != TableStatus.ACTIVE) + ; } private static TableStatus getTableStatus(String lockTable) { - return dynamodb.describeTable(DescribeTableRequest.builder().tableName(lockTable).build()).table().tableStatus(); + return dynamodb.describeTable( + DescribeTableRequest.builder().tableName(lockTable).build()) + .table() + .tableStatus(); } /** @@ -82,25 +80,28 @@ private static TableStatus getTableStatus(String lockTable) { * @return A DynamoDbClient pointing to the local DynamoDb instance */ static DynamoDbClient createClient() { - String endpoint = "http://" + dynamoDbContainer.getContainerIpAddress() + ":" + dynamoDbContainer.getFirstMappedPort(); + String endpoint = + "http://" + dynamoDbContainer.getContainerIpAddress() + ":" + dynamoDbContainer.getFirstMappedPort(); return DynamoDbClient.builder() - .endpointOverride(URI.create(endpoint)) - // The region is meaningless for local DynamoDb but required for client builder validation - .region(Region.US_EAST_1) - .credentialsProvider(StaticCredentialsProvider.create( - AwsBasicCredentials.create("dummy-key", "dummy-secret")) - ) - .build(); + .endpointOverride(URI.create(endpoint)) + // The region is meaningless for local DynamoDb but required for client builder + // validation + .region(Region.US_EAST_1) + .credentialsProvider( + StaticCredentialsProvider.create(AwsBasicCredentials.create("dummy-key", "dummy-secret"))) + .build(); } @AfterEach public void truncateLockTable() { - List> items = dynamodb.scan(ScanRequest.builder().tableName(TABLE_NAME).build()).items(); + List> items = dynamodb.scan( + ScanRequest.builder().tableName(TABLE_NAME).build()) + .items(); for (Map item : items) { dynamodb.deleteItem(DeleteItemRequest.builder() - .tableName(TABLE_NAME) - .key(Collections.singletonMap(ID, item.get(ID))) - .build()); + .tableName(TABLE_NAME) + .key(Collections.singletonMap(ID, item.get(ID))) + .build()); } } @@ -135,11 +136,10 @@ private Instant fromIsoString(String isoString) { private Map getLockItem(String lockName) { GetItemRequest request = GetItemRequest.builder() - .tableName(TABLE_NAME) - .key(Collections.singletonMap(ID, AttributeValue.builder() - .s(lockName) - .build())) - .build(); + .tableName(TABLE_NAME) + .key(Collections.singletonMap( + ID, AttributeValue.builder().s(lockName).build())) + .build(); GetItemResponse response = dynamodb.getItem(request); return response.item(); } diff --git a/providers/elasticsearch/shedlock-provider-elasticsearch8/src/main/java/net/javacrumbs/shedlock/provider/elasticsearch8/ElasticsearchLockProvider.java b/providers/elasticsearch/shedlock-provider-elasticsearch8/src/main/java/net/javacrumbs/shedlock/provider/elasticsearch8/ElasticsearchLockProvider.java index 37225855c..2fde85ab0 100644 --- a/providers/elasticsearch/shedlock-provider-elasticsearch8/src/main/java/net/javacrumbs/shedlock/provider/elasticsearch8/ElasticsearchLockProvider.java +++ b/providers/elasticsearch/shedlock-provider-elasticsearch8/src/main/java/net/javacrumbs/shedlock/provider/elasticsearch8/ElasticsearchLockProvider.java @@ -1,20 +1,21 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.elasticsearch8; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static net.javacrumbs.shedlock.support.Utils.getHostname; + import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.elasticsearch._types.ElasticsearchException; import co.elastic.clients.elasticsearch._types.Refresh; @@ -22,6 +23,11 @@ import co.elastic.clients.elasticsearch.core.UpdateRequest; import co.elastic.clients.elasticsearch.core.UpdateResponse; import co.elastic.clients.json.JsonData; +import java.io.IOException; +import java.time.Instant; +import java.util.Collections; +import java.util.Map; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; @@ -30,18 +36,9 @@ import net.javacrumbs.shedlock.support.annotation.NonNull; import org.elasticsearch.client.ResponseException; -import java.io.IOException; -import java.time.Instant; -import java.util.Collections; -import java.util.Map; -import java.util.Optional; - -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static net.javacrumbs.shedlock.support.Utils.getHostname; - /** - *

* It uses a collection that contains documents like this: + * *

  * {
  *    "name" : "lock name",
@@ -56,23 +53,20 @@
  *    "lockedBy" : "hostname"
  * }
  * 
+ * *

- * lockedAt and lockedBy are just for troubleshooting and are not read by the code + * lockedAt and lockedBy are just for troubleshooting and are not read by the + * code * *

    - *
  1. - * Attempts to insert a new lock record. As an optimization, we keep in-memory track of created lock records. If the record - * has been inserted, returns lock. - *
  2. - *
  3. - * We will try to update lock record using filter _id == name AND lock_until <= now - *
  4. - *
  5. - * If the update succeeded (1 updated document), we have the lock. If the update failed (0 updated documents) somebody else holds the lock - *
  6. - *
  7. - * When unlocking, lock_until is set to now. - *
  8. + *
  9. Attempts to insert a new lock record. As an optimization, we keep + * in-memory track of created lock records. If the record has been inserted, + * returns lock. + *
  10. We will try to update lock record using filter _id == name AND lock_until + * <= now + *
  11. If the update succeeded (1 updated document), we have the lock. If the + * update failed (0 updated documents) somebody else holds the lock + *
  12. When unlocking, lock_until is set to now. *
*/ public class ElasticsearchLockProvider implements LockProvider { @@ -82,15 +76,10 @@ public class ElasticsearchLockProvider implements LockProvider { static final String LOCKED_BY = "lockedBy"; static final String NAME = "name"; - - private static final String UPDATE_SCRIPT = - "if (ctx._source." + LOCK_UNTIL + " <= " + "params." + LOCKED_AT + ") { " + - "ctx._source." + LOCKED_BY + " = params." + LOCKED_BY + "; " + - "ctx._source." + LOCKED_AT + " = params." + LOCKED_AT + "; " + - "ctx._source." + LOCK_UNTIL + " = params." + LOCK_UNTIL + "; " + - "} else { " + - "ctx.op = 'none' " + - "}"; + private static final String UPDATE_SCRIPT = "if (ctx._source." + LOCK_UNTIL + " <= " + "params." + LOCKED_AT + + ") { " + "ctx._source." + LOCKED_BY + " = params." + LOCKED_BY + "; " + "ctx._source." + LOCKED_AT + + " = params." + LOCKED_AT + "; " + "ctx._source." + LOCK_UNTIL + " = params." + LOCK_UNTIL + "; " + + "} else { " + "ctx.op = 'none' " + "}"; private final ElasticsearchClient client; private final String hostname; @@ -112,28 +101,32 @@ public Optional lock(@NonNull LockConfiguration lockConfiguration) { try { Instant now = now(); Instant lockAtMostUntil = lockConfiguration.getLockAtMostUntil(); - Map lockObject = - lockObject(lockConfiguration.getName(), lockAtMostUntil, now); + Map lockObject = lockObject(lockConfiguration.getName(), lockAtMostUntil, now); // The object exist only to have some type we can work with Lock pojo = new Lock(lockConfiguration.getName(), hostname, now, lockAtMostUntil); - UpdateRequest updateRequest = UpdateRequest.of(ur -> ur - .index(index) - .id(lockConfiguration.getName()) - .refresh(Refresh.True) - .script(sc -> sc.inline(in -> in.lang("painless").source(UPDATE_SCRIPT).params(lockObject))) - .upsert(pojo)); + UpdateRequest updateRequest = UpdateRequest.of(ur -> ur.index(index) + .id(lockConfiguration.getName()) + .refresh(Refresh.True) + .script(sc -> sc.inline( + in -> in.lang("painless").source(UPDATE_SCRIPT).params(lockObject))) + .upsert(pojo)); UpdateResponse res = client.update(updateRequest, Lock.class); if (res.result() != Result.NoOp) { return Optional.of(new ElasticsearchSimpleLock(lockConfiguration)); - } else { //nothing happened + } else { // nothing happened return Optional.empty(); } } catch (IOException | ElasticsearchException e) { - if ((e instanceof ElasticsearchException && ((ElasticsearchException)e).status() == 409) || - (e instanceof ResponseException && ((ResponseException)e).getResponse().getStatusLine().getStatusCode() == 409)) { + if ((e instanceof ElasticsearchException && ((ElasticsearchException) e).status() == 409) + || (e instanceof ResponseException + && ((ResponseException) e) + .getResponse() + .getStatusLine() + .getStatusCode() + == 409)) { return Optional.empty(); } else { throw new LockException("Unexpected exception occurred", e); @@ -143,11 +136,14 @@ public Optional lock(@NonNull LockConfiguration lockConfiguration) { private Map lockObject(String name, Instant lockUntil, Instant lockedAt) { return Map.of( - NAME, JsonData.of(name), - LOCKED_BY, JsonData.of(hostname), - LOCKED_AT, JsonData.of(lockedAt.toEpochMilli()), - LOCK_UNTIL, JsonData.of(lockUntil.toEpochMilli()) - ); + NAME, + JsonData.of(name), + LOCKED_BY, + JsonData.of(hostname), + LOCKED_AT, + JsonData.of(lockedAt.toEpochMilli()), + LOCK_UNTIL, + JsonData.of(lockUntil.toEpochMilli())); } private final class ElasticsearchSimpleLock extends AbstractSimpleLock { @@ -160,14 +156,16 @@ private ElasticsearchSimpleLock(LockConfiguration lockConfiguration) { public void doUnlock() { // Set lockUtil to now or lockAtLeastUntil whichever is later try { - Map lockObject = Collections.singletonMap("unlockTime", JsonData.of(lockConfiguration.getUnlockTime().toEpochMilli())); + Map lockObject = Collections.singletonMap( + "unlockTime", + JsonData.of(lockConfiguration.getUnlockTime().toEpochMilli())); - UpdateRequest updateRequest = UpdateRequest.of(ur -> ur - .index(index) + UpdateRequest updateRequest = UpdateRequest.of(ur -> ur.index(index) .id(lockConfiguration.getName()) .refresh(Refresh.True) - .script(sc -> sc.inline(in -> in.lang("painless").source("ctx._source.lockUntil = params.unlockTime") - .params(lockObject)))); + .script(sc -> sc.inline(in -> in.lang("painless") + .source("ctx._source.lockUntil = params.unlockTime") + .params(lockObject)))); client.update(updateRequest, Lock.class); } catch (IOException | ElasticsearchException e) { throw new LockException("Unexpected exception occurred", e); diff --git a/providers/elasticsearch/shedlock-provider-elasticsearch8/src/test/java/net/javacrumbs/shedlock/provider/elasticsearch8/ElasticsearchLockProviderTest.java b/providers/elasticsearch/shedlock-provider-elasticsearch8/src/test/java/net/javacrumbs/shedlock/provider/elasticsearch8/ElasticsearchLockProviderTest.java index 4459c9e3e..e0891987b 100644 --- a/providers/elasticsearch/shedlock-provider-elasticsearch8/src/test/java/net/javacrumbs/shedlock/provider/elasticsearch8/ElasticsearchLockProviderTest.java +++ b/providers/elasticsearch/shedlock-provider-elasticsearch8/src/test/java/net/javacrumbs/shedlock/provider/elasticsearch8/ElasticsearchLockProviderTest.java @@ -1,20 +1,26 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.elasticsearch8; +import static net.javacrumbs.shedlock.provider.elasticsearch8.ElasticsearchLockProvider.LOCKED_AT; +import static net.javacrumbs.shedlock.provider.elasticsearch8.ElasticsearchLockProvider.LOCKED_BY; +import static net.javacrumbs.shedlock.provider.elasticsearch8.ElasticsearchLockProvider.LOCK_UNTIL; +import static net.javacrumbs.shedlock.provider.elasticsearch8.ElasticsearchLockProvider.NAME; +import static net.javacrumbs.shedlock.provider.elasticsearch8.ElasticsearchLockProvider.SCHEDLOCK_DEFAULT_INDEX; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.elasticsearch.core.GetRequest; import co.elastic.clients.elasticsearch.core.GetResponse; @@ -25,6 +31,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; +import java.io.IOException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.Map; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.test.support.AbstractLockProviderIntegrationTest; import org.apache.http.HttpHost; @@ -39,28 +50,16 @@ import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.Map; - -import static net.javacrumbs.shedlock.provider.elasticsearch8.ElasticsearchLockProvider.LOCKED_AT; -import static net.javacrumbs.shedlock.provider.elasticsearch8.ElasticsearchLockProvider.LOCKED_BY; -import static net.javacrumbs.shedlock.provider.elasticsearch8.ElasticsearchLockProvider.LOCK_UNTIL; -import static net.javacrumbs.shedlock.provider.elasticsearch8.ElasticsearchLockProvider.NAME; -import static net.javacrumbs.shedlock.provider.elasticsearch8.ElasticsearchLockProvider.SCHEDLOCK_DEFAULT_INDEX; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; - @Testcontainers public class ElasticsearchLockProviderTest extends AbstractLockProviderIntegrationTest { - private static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("docker.elastic.co/elasticsearch/elasticsearch"); + private static final DockerImageName DEFAULT_IMAGE_NAME = + DockerImageName.parse("docker.elastic.co/elasticsearch/elasticsearch"); @Container private static final ElasticsearchContainer container = - new ElasticsearchContainer(DEFAULT_IMAGE_NAME.withTag("7.17.5")).withPassword("elastic1234"); + new ElasticsearchContainer(DEFAULT_IMAGE_NAME.withTag("7.17.5")).withPassword("elastic1234"); + private ElasticsearchClient client; private ElasticsearchLockProvider lockProvider; @@ -68,10 +67,10 @@ public class ElasticsearchLockProviderTest extends AbstractLockProviderIntegrati public void setUp() { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "elastic1234")); - RestClient restClient = RestClient.builder( - HttpHost.create(container.getHttpHostAddress())) - .setHttpClientConfigCallback(clientBuilder -> clientBuilder.setDefaultCredentialsProvider(credentialsProvider)) - .build(); + RestClient restClient = RestClient.builder(HttpHost.create(container.getHttpHostAddress())) + .setHttpClientConfigCallback( + clientBuilder -> clientBuilder.setDefaultCredentialsProvider(credentialsProvider)) + .build(); ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper(objectMapper())); client = new ElasticsearchClient(transport); lockProvider = new ElasticsearchLockProvider(client); @@ -79,11 +78,11 @@ public void setUp() { private ObjectMapper objectMapper() { JavaTimeModule module = new JavaTimeModule(); - module.addSerializer(LocalDateTime.class, - new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); + module.addSerializer( + LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); return new ObjectMapper() - .setSerializationInclusion(JsonInclude.Include.NON_NULL) - .registerModule(module); + .setSerializationInclusion(JsonInclude.Include.NON_NULL) + .registerModule(module); } @Override @@ -93,13 +92,12 @@ protected LockProvider getLockProvider() { @Override protected void assertUnlocked(String lockName) { - GetRequest request = GetRequest.of(gr -> gr - .index(SCHEDLOCK_DEFAULT_INDEX) - .id(lockName)); + GetRequest request = + GetRequest.of(gr -> gr.index(SCHEDLOCK_DEFAULT_INDEX).id(lockName)); try { GetResponse response = client.get(request, Map.class); Map source = response.source(); - assertThat(new Date((Long)source.get(LOCK_UNTIL))).isBeforeOrEqualsTo(now()); + assertThat(new Date((Long) source.get(LOCK_UNTIL))).isBeforeOrEqualsTo(now()); assertThat(new Date((Long) source.get(LOCKED_AT))).isBeforeOrEqualsTo(now()); assertThat((String) source.get(LOCKED_BY)).isNotBlank(); assertThat((String) source.get(NAME)).isEqualTo(lockName); @@ -110,9 +108,8 @@ protected void assertUnlocked(String lockName) { @Override protected void assertLocked(String lockName) { - GetRequest request = GetRequest.of(gr -> gr - .index(SCHEDLOCK_DEFAULT_INDEX) - .id(lockName)); + GetRequest request = + GetRequest.of(gr -> gr.index(SCHEDLOCK_DEFAULT_INDEX).id(lockName)); try { GetResponse response = client.get(request, Map.class); Map source = response.source(); @@ -128,5 +125,4 @@ protected void assertLocked(String lockName) { private Date now() { return new Date(); } - } diff --git a/providers/etcd/shedlock-provider-etcd-jetcd/src/main/java/net/javacrumbs/shedlock/provider/etcd/jetcd/EtcdLockProvider.java b/providers/etcd/shedlock-provider-etcd-jetcd/src/main/java/net/javacrumbs/shedlock/provider/etcd/jetcd/EtcdLockProvider.java index 04b0ac40b..97b5e2ade 100644 --- a/providers/etcd/shedlock-provider-etcd-jetcd/src/main/java/net/javacrumbs/shedlock/provider/etcd/jetcd/EtcdLockProvider.java +++ b/providers/etcd/shedlock-provider-etcd-jetcd/src/main/java/net/javacrumbs/shedlock/provider/etcd/jetcd/EtcdLockProvider.java @@ -1,20 +1,23 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.etcd.jetcd; +import static io.etcd.jetcd.options.GetOption.DEFAULT; +import static java.nio.charset.StandardCharsets.UTF_8; +import static net.javacrumbs.shedlock.support.Utils.getHostname; +import static net.javacrumbs.shedlock.support.Utils.toIsoString; + import io.etcd.jetcd.ByteSequence; import io.etcd.jetcd.Client; import io.etcd.jetcd.KV; @@ -25,6 +28,9 @@ import io.etcd.jetcd.op.CmpTarget; import io.etcd.jetcd.op.Op; import io.etcd.jetcd.options.PutOption; +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; @@ -33,21 +39,15 @@ import net.javacrumbs.shedlock.support.LockException; import net.javacrumbs.shedlock.support.annotation.NonNull; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; - -import static io.etcd.jetcd.options.GetOption.DEFAULT; -import static java.nio.charset.StandardCharsets.UTF_8; -import static net.javacrumbs.shedlock.support.Utils.getHostname; -import static net.javacrumbs.shedlock.support.Utils.toIsoString; - /** * Uses etcd keys and the version of the key value pairs as locking mechanism. + * *

* https://etcd.io/docs/v3.4.0/learning/api/#key-value-pair * - * The timeout is implemented with the lease concept of etcd, which grants a TTL for key value pairs. + *

+ * The timeout is implemented with the lease concept of etcd, which grants a TTL + * for key value pairs. */ public class EtcdLockProvider implements LockProvider { private static final double MILLIS_IN_SECOND = 1000; @@ -77,7 +77,6 @@ public Optional lock(@NonNull LockConfiguration lockConfiguration) { Optional leaseIdOpt = etcdTemplate.tryToLock(key, value, lockConfiguration.getLockAtMostUntil()); return leaseIdOpt.map(leaseId -> new EtcdLock(key, value, leaseId, etcdTemplate, lockConfiguration)); - } private static long getSecondsUntil(Instant instant) { @@ -102,7 +101,12 @@ private static final class EtcdLock extends AbstractSimpleLock { private final Long successLeaseId; private final EtcdTemplate etcdTemplate; - private EtcdLock(String key, String value, Long successLeaseId, EtcdTemplate etcdTemplate, LockConfiguration lockConfiguration) { + private EtcdLock( + String key, + String value, + Long successLeaseId, + EtcdTemplate etcdTemplate, + LockConfiguration lockConfiguration) { super(lockConfiguration); this.key = key; this.value = value; @@ -157,11 +161,13 @@ public Optional tryToLock(String key, String value, Instant lockAtMostUnti PutOption putOption = putOptionWithLeaseId(leaseId); // Version is the version of the key. - // A deletion resets the version to zero and any modification of the key increases its version. + // A deletion resets the version to zero and any modification of the key + // increases its + // version. Txn txn = kvClient.txn() - .If(new Cmp(lockKey, Cmp.Op.EQUAL, CmpTarget.version(0))) - .Then(Op.put(lockKey, toByteSequence(value), putOption)) - .Else(Op.get(lockKey, DEFAULT)); + .If(new Cmp(lockKey, Cmp.Op.EQUAL, CmpTarget.version(0))) + .Then(Op.put(lockKey, toByteSequence(value), putOption)) + .Else(Op.get(lockKey, DEFAULT)); TxnResponse tr = txn.commit().get(); if (tr.isSucceeded()) { @@ -174,7 +180,6 @@ public Optional tryToLock(String key, String value, Instant lockAtMostUnti revoke(leaseId); throw new LockException("Failed to set lock " + key, e); } - } public void revoke(Long leaseId) { @@ -186,12 +191,15 @@ public void revoke(Long leaseId) { } /** - * Set the provided leaseId lease for the key-value pair similar to the CLI command + * Set the provided leaseId lease for the key-value pair similar to the CLI + * command + * *

* etcdctl put key value --lease + * *

- * If the key has already been put with an other leaseId earlier, the old leaseId - * will be timed out and then removed, eventually. + * If the key has already been put with an other leaseId earlier, the old + * leaseId will be timed out and then removed, eventually. */ public void putWithLeaseId(String key, String value, Long leaseId) { ByteSequence lockKey = toByteSequence(key); @@ -209,5 +217,4 @@ private PutOption putOptionWithLeaseId(Long leaseId) { return PutOption.newBuilder().withLeaseId(leaseId).build(); } } - } diff --git a/providers/etcd/shedlock-provider-etcd-jetcd/src/test/java/net/javacrumbs/shedlock/provider/etcd/jetcd/EtcdLockProviderIntegrationTest.java b/providers/etcd/shedlock-provider-etcd-jetcd/src/test/java/net/javacrumbs/shedlock/provider/etcd/jetcd/EtcdLockProviderIntegrationTest.java index 8d513ddc9..efcab26e5 100644 --- a/providers/etcd/shedlock-provider-etcd-jetcd/src/test/java/net/javacrumbs/shedlock/provider/etcd/jetcd/EtcdLockProviderIntegrationTest.java +++ b/providers/etcd/shedlock-provider-etcd-jetcd/src/test/java/net/javacrumbs/shedlock/provider/etcd/jetcd/EtcdLockProviderIntegrationTest.java @@ -1,20 +1,23 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.etcd.jetcd; +import static java.time.Duration.ofSeconds; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.fail; + import io.etcd.jetcd.ByteSequence; import io.etcd.jetcd.Client; import io.etcd.jetcd.KV; @@ -28,11 +31,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static java.time.Duration.ofSeconds; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.awaitility.Awaitility.await; -import static org.junit.jupiter.api.Assertions.fail; - public class EtcdLockProviderIntegrationTest extends AbstractLockProviderIntegrationTest { private static final EtcdCluster cluster = new Etcd.Builder().withNodes(1).build(); @@ -72,18 +70,14 @@ private void warmUpLeaseClient(Client client) { } } - /** - * Modified for etcd, since its lease grants only suppport TTL in seconds - */ + /** Modified for etcd, since its lease grants only suppport TTL in seconds */ @Test @Override public void shouldTimeout() throws InterruptedException { doTestTimeout(ofSeconds(1)); } - /** - * Modified for etcd, since its lease grants only suppport TTL in seconds - */ + /** Modified for etcd, since its lease grants only suppport TTL in seconds */ @Test @Override public void shouldLockAtLeastFor() throws InterruptedException { @@ -121,5 +115,4 @@ protected LockProvider getLockProvider() { private Client buildClient() { return Client.builder().endpoints(cluster.clientEndpoints()).build(); } - } diff --git a/providers/hazelcast/shedlock-provider-hazelcast4/src/main/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLock.java b/providers/hazelcast/shedlock-provider-hazelcast4/src/main/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLock.java index 46736815f..ad68709b6 100644 --- a/providers/hazelcast/shedlock-provider-hazelcast4/src/main/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLock.java +++ b/providers/hazelcast/shedlock-provider-hazelcast4/src/main/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLock.java @@ -1,27 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.hazelcast4; -import net.javacrumbs.shedlock.core.LockConfiguration; - import java.io.Serializable; import java.time.Instant; +import net.javacrumbs.shedlock.core.LockConfiguration; /** * Hazelcast lock entity. + * *

* It's used to persist lock information into Hazelcast instances (cluster). */ @@ -34,12 +32,16 @@ class HazelcastLock implements Serializable { private final Instant lockAtLeastUntil; /** - * Moment when the lock is expired, so unlockable. - * The first value of this is {@link #lockAtMostUntil}. + * Moment when the lock is expired, so unlockable. The first value of this is + * {@link #lockAtMostUntil}. */ private final Instant timeToLive; - private HazelcastLock(final String name, final Instant lockAtMostUntil, final Instant lockAtLeastUntil, final Instant timeToLive) { + private HazelcastLock( + final String name, + final Instant lockAtMostUntil, + final Instant lockAtLeastUntil, + final Instant timeToLive) { this.name = name; this.lockAtMostUntil = lockAtMostUntil; this.lockAtLeastUntil = lockAtLeastUntil; @@ -51,13 +53,18 @@ boolean isExpired(Instant now) { } /** - * Instantiate {@link HazelcastLock} with {@link LockConfiguration} and Hazelcast member UUID. + * Instantiate {@link HazelcastLock} with {@link LockConfiguration} and + * Hazelcast member UUID. * * @param configuration * @return the new instance of {@link HazelcastLock}. */ static HazelcastLock fromConfigurationWhereTtlIsUntilTime(final LockConfiguration configuration) { - return new HazelcastLock(configuration.getName(), configuration.getLockAtMostUntil(), configuration.getLockAtLeastUntil(), configuration.getLockAtMostUntil()); + return new HazelcastLock( + configuration.getName(), + configuration.getLockAtMostUntil(), + configuration.getLockAtLeastUntil(), + configuration.getLockAtMostUntil()); } /** @@ -84,12 +91,7 @@ Instant getTimeToLive() { @Override public String toString() { - return "HazelcastLock{" + - "name='" + name + '\'' + - ", lockAtMostUntil=" + lockAtMostUntil + - ", lockAtLeastUntil=" + lockAtLeastUntil + - ", timeToLive=" + timeToLive + - '}'; + return "HazelcastLock{" + "name='" + name + '\'' + ", lockAtMostUntil=" + lockAtMostUntil + + ", lockAtLeastUntil=" + lockAtLeastUntil + ", timeToLive=" + timeToLive + '}'; } - } diff --git a/providers/hazelcast/shedlock-provider-hazelcast4/src/main/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLockProvider.java b/providers/hazelcast/shedlock-provider-hazelcast4/src/main/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLockProvider.java index f3edab5d2..6d3b72d8c 100644 --- a/providers/hazelcast/shedlock-provider-hazelcast4/src/main/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLockProvider.java +++ b/providers/hazelcast/shedlock-provider-hazelcast4/src/main/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLockProvider.java @@ -1,22 +1,24 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.hazelcast4; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.map.IMap; +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; +import java.util.concurrent.TimeUnit; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; @@ -25,27 +27,27 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; -import java.util.concurrent.TimeUnit; - /** * HazelcastLockProvider. + * *

- * Implementation of {@link LockProvider} using Hazelcast for storing and sharing lock information and mechanisms between a cluster's members + * Implementation of {@link LockProvider} using Hazelcast for storing and + * sharing lock information and mechanisms between a cluster's members + * *

- * Below, the mechanisms : - * - The Lock, an instance of {@link HazelcastLock}, is obtained / created when : - * -- the lock is not already locked by other process (lock - referenced by its name - is not present in the Hazelcast locks store OR unlockable) - * -- the lock is expired : {@link Instant#now()} > {@link HazelcastLock#timeToLive} where unlockTime have by default the same value of {@link HazelcastLock#lockAtMostUntil} - * and can have the value of {@link HazelcastLock#lockAtLeastUntil} if unlock action is used - * --- expired object is removed - * -- the lock is owned by not available member of Hazelcast cluster member - * --- no owner object is removed - * - Unlock action : - * -- removes lock object when {@link HazelcastLock#lockAtLeastUntil} is not come - * -- override value of {@link HazelcastLock#timeToLive} with {@link HazelcastLock#lockAtLeastUntil} (its default value is the same of {@link HazelcastLock#lockAtLeastUntil} + * Below, the mechanisms : - The Lock, an instance of {@link HazelcastLock}, is + * obtained / created when : -- the lock is not already locked by other process + * (lock - referenced by its name - is not present in the Hazelcast locks store + * OR unlockable) -- the lock is expired : {@link Instant#now()} > + * {@link HazelcastLock#timeToLive} where unlockTime have by default the same + * value of {@link HazelcastLock#lockAtMostUntil} and can have the value of + * {@link HazelcastLock#lockAtLeastUntil} if unlock action is used --- expired + * object is removed -- the lock is owned by not available member of Hazelcast + * cluster member --- no owner object is removed - Unlock action : -- removes + * lock object when {@link HazelcastLock#lockAtLeastUntil} is not come -- + * override value of {@link HazelcastLock#timeToLive} with + * {@link HazelcastLock#lockAtLeastUntil} (its default value is the same of + * {@link HazelcastLock#lockAtLeastUntil} */ public class HazelcastLockProvider implements LockProvider { @@ -55,14 +57,12 @@ public class HazelcastLockProvider implements LockProvider { private static final Duration DEFAULT_LOCK_LEASE_TIME = Duration.ofSeconds(30); /** - * Key used for get the lock container (an {@link IMap}) inside {@link #hazelcastInstance}. - * By default : {@link #LOCK_STORE_KEY_DEFAULT} + * Key used for get the lock container (an {@link IMap}) inside + * {@link #hazelcastInstance}. By default : {@link #LOCK_STORE_KEY_DEFAULT} */ private final String lockStoreKey; - /** - * Instance of the Hazelcast engine used by the application. - */ + /** Instance of the Hazelcast engine used by the application. */ private final HazelcastInstance hazelcastInstance; private final long lockLeaseTimeMs; @@ -70,7 +70,8 @@ public class HazelcastLockProvider implements LockProvider { /** * Instantiate the provider. * - * @param hazelcastInstance The Hazelcast engine used by the application. + * @param hazelcastInstance + * The Hazelcast engine used by the application. */ public HazelcastLockProvider(@NonNull HazelcastInstance hazelcastInstance) { this(hazelcastInstance, LOCK_STORE_KEY_DEFAULT); @@ -79,8 +80,11 @@ public HazelcastLockProvider(@NonNull HazelcastInstance hazelcastInstance) { /** * Instantiate the provider. * - * @param hazelcastInstance The Hazelcast engine used by the application - * @param lockStoreKey The key where the locks are stored (by default {@link #LOCK_STORE_KEY_DEFAULT}). + * @param hazelcastInstance + * The Hazelcast engine used by the application + * @param lockStoreKey + * The key where the locks are stored (by default + * {@link #LOCK_STORE_KEY_DEFAULT}). */ public HazelcastLockProvider(@NonNull HazelcastInstance hazelcastInstance, @NonNull String lockStoreKey) { this(hazelcastInstance, lockStoreKey, DEFAULT_LOCK_LEASE_TIME); @@ -89,13 +93,21 @@ public HazelcastLockProvider(@NonNull HazelcastInstance hazelcastInstance, @NonN /** * Instantiate the provider. * - * @param hazelcastInstance The com.hazelcast.core.Hazelcast engine used by the application - * @param lockStoreKey The key where the locks are stored (by default {@link #LOCK_STORE_KEY_DEFAULT}). - * @param lockLeaseTime When lock is being obtained there is a Hazelcast lock used to make it thread-safe. - * This lock should be released quite fast but if the process dies while holding the lock, it is held forever. - * lockLeaseTime is used as a safety-net for such situations. + * @param hazelcastInstance + * The com.hazelcast.core.Hazelcast engine used by the application + * @param lockStoreKey + * The key where the locks are stored (by default + * {@link #LOCK_STORE_KEY_DEFAULT}). + * @param lockLeaseTime + * When lock is being obtained there is a Hazelcast lock used to make + * it thread-safe. This lock should be released quite fast but if the + * process dies while holding the lock, it is held forever. + * lockLeaseTime is used as a safety-net for such situations. */ - public HazelcastLockProvider(@NonNull HazelcastInstance hazelcastInstance, @NonNull String lockStoreKey, @NonNull Duration lockLeaseTime) { + public HazelcastLockProvider( + @NonNull HazelcastInstance hazelcastInstance, + @NonNull String lockStoreKey, + @NonNull Duration lockLeaseTime) { this.hazelcastInstance = hazelcastInstance; this.lockStoreKey = lockStoreKey; this.lockLeaseTimeMs = lockLeaseTime.toMillis(); @@ -136,7 +148,8 @@ private boolean tryLock(final LockConfiguration lockConfiguration, final Instant addNewLock(lockConfiguration); return true; } else if (lock.isExpired(now)) { - log.debug("lock - lock obtained, it was locked but expired : oldLock={}; conf={}", lock, lockConfiguration); + log.debug( + "lock - lock obtained, it was locked but expired : oldLock={}; conf={}", lock, lockConfiguration); replaceLock(lockName, lockConfiguration); return true; } else { @@ -145,7 +158,6 @@ private boolean tryLock(final LockConfiguration lockConfiguration, final Instant } } - private IMap getStore() { return hazelcastInstance.getMap(lockStoreKey); } @@ -180,7 +192,8 @@ private boolean isUnlocked(final HazelcastLock lock) { /** * Unlock the lock with its name. * - * @param lockConfiguration the name of the lock to unlock. + * @param lockConfiguration + * the name of the lock to unlock. */ /* package */ void unlock(LockConfiguration lockConfiguration) { String lockName = lockConfiguration.getName(); @@ -211,6 +224,5 @@ private void unlockProperly(final HazelcastLock lock, final Instant now) { final HazelcastLock newLock = HazelcastLock.fromLockWhereTtlIsReduceToLeastTime(lock); getStore().put(lockName, newLock); } - } } diff --git a/providers/hazelcast/shedlock-provider-hazelcast4/src/main/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastSimpleLock.java b/providers/hazelcast/shedlock-provider-hazelcast4/src/main/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastSimpleLock.java index 69964116c..e3115bc1b 100644 --- a/providers/hazelcast/shedlock-provider-hazelcast4/src/main/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastSimpleLock.java +++ b/providers/hazelcast/shedlock-provider-hazelcast4/src/main/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastSimpleLock.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.hazelcast4; @@ -19,9 +17,7 @@ import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.SimpleLock; -/** - * Implementation of {@link SimpleLock} for unlock {@link HazelcastLock}. - */ +/** Implementation of {@link SimpleLock} for unlock {@link HazelcastLock}. */ class HazelcastSimpleLock extends AbstractSimpleLock { private final HazelcastLockProvider lockProvider; @@ -30,7 +26,6 @@ class HazelcastSimpleLock extends AbstractSimpleLock { this.lockProvider = lockProvider; } - @Override public void doUnlock() { lockProvider.unlock(lockConfiguration); diff --git a/providers/hazelcast/shedlock-provider-hazelcast4/src/test/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLockProviderClusterTest.java b/providers/hazelcast/shedlock-provider-hazelcast4/src/test/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLockProviderClusterTest.java index 5f7afafe2..1ddf76c67 100644 --- a/providers/hazelcast/shedlock-provider-hazelcast4/src/test/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLockProviderClusterTest.java +++ b/providers/hazelcast/shedlock-provider-hazelcast4/src/test/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLockProviderClusterTest.java @@ -1,23 +1,30 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.hazelcast4; +import static java.time.temporal.ChronoUnit.SECONDS; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import com.hazelcast.client.HazelcastClient; import com.hazelcast.core.Hazelcast; +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.SimpleLock; import org.junit.jupiter.api.AfterEach; @@ -25,17 +32,6 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -import static java.time.temporal.ChronoUnit.SECONDS; -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; - @Disabled public class HazelcastLockProviderClusterTest { @@ -85,7 +81,7 @@ public void testGetLocksByTwoMembersOfCluster() { assertUnlocked(lockProvider1, LOCK_NAME_2); } - private void assertUnlocked(HazelcastLockProvider lockProvider, String lockName) { + private void assertUnlocked(HazelcastLockProvider lockProvider, String lockName) { HazelcastLock lock = lockProvider.getLock(lockName); if (lock != null) { Instant now = now(); @@ -108,7 +104,8 @@ public void testGetLockByLateMemberOfCluster() { @Test public void testGetLockInCluster() throws InterruptedException { - Optional lock1 = lockProvider1.lock(lockConfig(LOCK_NAME_1, Duration.of(5, SECONDS), Duration.of(3, SECONDS))); + Optional lock1 = + lockProvider1.lock(lockConfig(LOCK_NAME_1, Duration.of(5, SECONDS), Duration.of(3, SECONDS))); assertThat(lock1).isNotEmpty(); Optional lock2 = lockProvider2.lock(simpleLockConfig(LOCK_NAME_1)); assertThat(lock2).isEmpty(); diff --git a/providers/hazelcast/shedlock-provider-hazelcast4/src/test/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLockProviderIntegrationTest.java b/providers/hazelcast/shedlock-provider-hazelcast4/src/test/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLockProviderIntegrationTest.java index e3580ef2f..2355be690 100644 --- a/providers/hazelcast/shedlock-provider-hazelcast4/src/test/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLockProviderIntegrationTest.java +++ b/providers/hazelcast/shedlock-provider-hazelcast4/src/test/java/net/javacrumbs/shedlock/provider/hazelcast4/HazelcastLockProviderIntegrationTest.java @@ -1,20 +1,19 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.hazelcast4; +import static org.assertj.core.api.Assertions.assertThat; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; @@ -25,8 +24,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; -import static org.assertj.core.api.Assertions.assertThat; - public class HazelcastLockProviderIntegrationTest extends AbstractLockProviderIntegrationTest { private static HazelcastInstance hazelcastInstance; @@ -54,8 +51,10 @@ protected LockProvider getLockProvider() { return lockProvider; } - @Override - protected void assertUnlocked(final String lockName) { assertThat(isUnlocked(lockName)).isTrue(); } + @Override + protected void assertUnlocked(final String lockName) { + assertThat(isUnlocked(lockName)).isTrue(); + } private boolean isUnlocked(final String lockName) { final HazelcastLock lock = lockProvider.getLock(lockName); diff --git a/providers/ignite/shedlock-provider-ignite/src/main/java/net/javacrumbs/shedlock/provider/ignite/IgniteLockProvider.java b/providers/ignite/shedlock-provider-ignite/src/main/java/net/javacrumbs/shedlock/provider/ignite/IgniteLockProvider.java index f9b5d78c3..c07a54a29 100644 --- a/providers/ignite/shedlock-provider-ignite/src/main/java/net/javacrumbs/shedlock/provider/ignite/IgniteLockProvider.java +++ b/providers/ignite/shedlock-provider-ignite/src/main/java/net/javacrumbs/shedlock/provider/ignite/IgniteLockProvider.java @@ -1,20 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.ignite; +import static net.javacrumbs.shedlock.support.Utils.getHostname; + +import java.time.Instant; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ExtensibleLockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; @@ -22,50 +24,39 @@ import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; -import java.time.Instant; -import java.util.Optional; - -import static net.javacrumbs.shedlock.support.Utils.getHostname; - /** * Distributed lock using Apache Ignite. + * *

* It uses a {@link String} key (lock name) and {@link LockValue} value. - *

* - *

lockedAt and lockedBy are just for troubleshooting and are not read by the code.

+ *

+ * lockedAt and lockedBy are just for troubleshooting and are not read by the + * code. Creating a lock: * - * Creating a lock: *

    - *
  1. - * If there is no locks with given name, try to use {@link IgniteCache#putIfAbsent}. - *
  2. - *
  3. - * If there is a lock with given name, and its lockUntil is before or equal {@code now}, - * try to use {@link IgniteCache#replace}. - *
  4. - *
  5. - * Otherwise, return {@link Optional#empty}. - *
  6. + *
  7. If there is no locks with given name, try to use + * {@link IgniteCache#putIfAbsent}. + *
  8. If there is a lock with given name, and its lockUntil is before or equal + * {@code now}, try to use {@link IgniteCache#replace}. + *
  9. Otherwise, return {@link Optional#empty}. *
* * Extending a lock: + * *
    - *
  1. - * If there is a lock with given name and hostname, and its lockUntil is after {@code now}, try to use - * {@link IgniteCache#replace} to set lockUntil to {@link LockConfiguration#getLockAtMostUntil}. - *
  2. - *
  3. - * Otherwise, return {@link Optional#empty}. - *
  4. + *
  5. If there is a lock with given name and hostname, and its lockUntil is + * after {@code now}, try to use {@link IgniteCache#replace} to set lockUntil to + * {@link LockConfiguration#getLockAtMostUntil}. + *
  6. Otherwise, return {@link Optional#empty}. *
* * Unlock: + * *
    - *
  1. - * If there is a lock with given name and hostname, try to use {@link IgniteCache#replace} to set lockUntil to + *
  2. If there is a lock with given name and hostname, try to use + * {@link IgniteCache#replace} to set lockUntil to * {@link LockConfiguration#getUnlockTime}. - *
  3. *
*/ public class IgniteLockProvider implements ExtensibleLockProvider { @@ -76,23 +67,24 @@ public class IgniteLockProvider implements ExtensibleLockProvider { private final IgniteCache cache; /** - * @param ignite Ignite instance. + * @param ignite + * Ignite instance. */ public IgniteLockProvider(Ignite ignite) { this(ignite, DEFAULT_SHEDLOCK_CACHE_NAME); } /** - * @param ignite Ignite instance. - * @param shedLockCacheName ShedLock cache name to use instead of default. + * @param ignite + * Ignite instance. + * @param shedLockCacheName + * ShedLock cache name to use instead of default. */ public IgniteLockProvider(Ignite ignite, String shedLockCacheName) { this.cache = ignite.getOrCreateCache(shedLockCacheName); } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public Optional lock(LockConfiguration lockCfg) { Instant now = Instant.now(); @@ -102,8 +94,7 @@ public Optional lock(LockConfiguration lockCfg) { LockValue oldVal = cache.get(key); if (oldVal == null) { - if (cache.putIfAbsent(key, newVal)) - return Optional.of(new IgniteLock(lockCfg, this)); + if (cache.putIfAbsent(key, newVal)) return Optional.of(new IgniteLock(lockCfg, this)); return Optional.empty(); } @@ -115,10 +106,12 @@ public Optional lock(LockConfiguration lockCfg) { } /** - * If there is a lock with given name and hostname, try to use {@link IgniteCache#replace} to set lockUntil to + * If there is a lock with given name and hostname, try to use + * {@link IgniteCache#replace} to set lockUntil to * {@link LockConfiguration#getLockAtMostUntil}. * - * @param lockCfg Lock configuration. + * @param lockCfg + * Lock configuration. * @return New lock if succeed extended. Empty, otherwise. */ private Optional extend(LockConfiguration lockCfg) { @@ -127,22 +120,23 @@ private Optional extend(LockConfiguration lockCfg) { String key = lockCfg.getName(); LockValue oldVal = cache.get(key); - if (oldVal == null || !oldVal.getLockedBy().equals(getHostname()) || !oldVal.getLockUntil().isAfter(now)) - return Optional.empty(); + if (oldVal == null + || !oldVal.getLockedBy().equals(getHostname()) + || !oldVal.getLockUntil().isAfter(now)) return Optional.empty(); LockValue newVal = oldVal.withLockUntil(lockCfg.getLockAtMostUntil()); - if (cache.replace(key, oldVal, newVal)) - return Optional.of(new IgniteLock(lockCfg, this)); + if (cache.replace(key, oldVal, newVal)) return Optional.of(new IgniteLock(lockCfg, this)); return Optional.empty(); } /** - * If there is a lock with given name and hostname, try to use {@link IgniteCache#replace} to set lockUntil to - * {@code now}. + * If there is a lock with given name and hostname, try to use + * {@link IgniteCache#replace} to set lockUntil to {@code now}. * - * @param lockCfg Lock configuration. + * @param lockCfg + * Lock configuration. */ private void unlock(LockConfiguration lockCfg) { String key = lockCfg.getName(); @@ -155,16 +149,16 @@ private void unlock(LockConfiguration lockCfg) { } } - /** - * Ignite lock. - */ + /** Ignite lock. */ private static final class IgniteLock extends AbstractSimpleLock { /** Ignite lock provider. */ private final IgniteLockProvider lockProvider; /** - * @param lockCfg Lock configuration. - * @param lockProvider Ignite lock provider. + * @param lockCfg + * Lock configuration. + * @param lockProvider + * Ignite lock provider. */ private IgniteLock(LockConfiguration lockCfg, IgniteLockProvider lockProvider) { super(lockCfg); diff --git a/providers/ignite/shedlock-provider-ignite/src/main/java/net/javacrumbs/shedlock/provider/ignite/LockValue.java b/providers/ignite/shedlock-provider-ignite/src/main/java/net/javacrumbs/shedlock/provider/ignite/LockValue.java index 773dc0c40..45f8814d7 100644 --- a/providers/ignite/shedlock-provider-ignite/src/main/java/net/javacrumbs/shedlock/provider/ignite/LockValue.java +++ b/providers/ignite/shedlock-provider-ignite/src/main/java/net/javacrumbs/shedlock/provider/ignite/LockValue.java @@ -1,25 +1,21 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.ignite; import java.time.Instant; -/** - * Value object for ShedLock cache. - */ +/** Value object for ShedLock cache. */ class LockValue { /** Locked at time. */ private final Instant lockedAt; @@ -31,9 +27,12 @@ class LockValue { private final String lockedBy; /** - * @param lockedAt Locked at time. - * @param lockUntil Locked until time. - * @param lockedBy Locked by hostname. + * @param lockedAt + * Locked at time. + * @param lockUntil + * Locked until time. + * @param lockedBy + * Locked by hostname. */ public LockValue(Instant lockedAt, Instant lockUntil, String lockedBy) { this.lockedAt = lockedAt; diff --git a/providers/ignite/shedlock-provider-ignite/src/test/java/net/javacrumbs/shedlock/provider/ignite/IgniteLockProviderTest.java b/providers/ignite/shedlock-provider-ignite/src/test/java/net/javacrumbs/shedlock/provider/ignite/IgniteLockProviderTest.java index eca4f2fbf..f7486b667 100644 --- a/providers/ignite/shedlock-provider-ignite/src/test/java/net/javacrumbs/shedlock/provider/ignite/IgniteLockProviderTest.java +++ b/providers/ignite/shedlock-provider-ignite/src/test/java/net/javacrumbs/shedlock/provider/ignite/IgniteLockProviderTest.java @@ -1,20 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.ignite; +import static net.javacrumbs.shedlock.provider.ignite.IgniteLockProvider.DEFAULT_SHEDLOCK_CACHE_NAME; +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Instant; import net.javacrumbs.shedlock.core.ExtensibleLockProvider; import net.javacrumbs.shedlock.test.support.AbstractExtensibleLockProviderIntegrationTest; import org.apache.ignite.Ignite; @@ -24,14 +26,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; -import java.time.Instant; - -import static net.javacrumbs.shedlock.provider.ignite.IgniteLockProvider.DEFAULT_SHEDLOCK_CACHE_NAME; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Test for {@link IgniteLockProvider}. - */ +/** Test for {@link IgniteLockProvider}. */ public class IgniteLockProviderTest extends AbstractExtensibleLockProviderIntegrationTest { private static Ignite ignite; private static IgniteCache cache; diff --git a/providers/inmemory/shedlock-provider-inmemory/src/main/java/net/javacrumbs/shedlock/provider/inmemory/InMemoryLockProvider.java b/providers/inmemory/shedlock-provider-inmemory/src/main/java/net/javacrumbs/shedlock/provider/inmemory/InMemoryLockProvider.java index 38309b401..d17605751 100644 --- a/providers/inmemory/shedlock-provider-inmemory/src/main/java/net/javacrumbs/shedlock/provider/inmemory/InMemoryLockProvider.java +++ b/providers/inmemory/shedlock-provider-inmemory/src/main/java/net/javacrumbs/shedlock/provider/inmemory/InMemoryLockProvider.java @@ -1,5 +1,11 @@ package net.javacrumbs.shedlock.provider.inmemory; +import static net.javacrumbs.shedlock.core.ClockProvider.now; + +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ExtensibleLockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; @@ -7,16 +13,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Instant; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -import static net.javacrumbs.shedlock.core.ClockProvider.now; - /** - * In memory lock that is suitable only for tests and running application locally. -*/ + * In memory lock that is suitable only for tests and running application + * locally. + */ public class InMemoryLockProvider implements ExtensibleLockProvider { private final Map locks = new HashMap<>(); @@ -31,7 +31,7 @@ public Optional lock(LockConfiguration lockConfiguration) { } else { LockRecord lockRecord = new LockRecord(lockConfiguration.getLockAtMostUntil()); locks.put(lockName, lockRecord); - logger.debug("Locked {}", lockConfiguration); + logger.debug("Locked {}", lockConfiguration); return Optional.of(new InMemoryLock(lockConfiguration)); } } @@ -46,7 +46,7 @@ boolean isLocked(String lockName) { private void doUnlock(LockConfiguration lockConfiguration) { synchronized (locks) { - locks.put(lockConfiguration.getName(), new LockRecord(lockConfiguration.getLockAtLeastUntil())); + locks.put(lockConfiguration.getName(), new LockRecord(lockConfiguration.getLockAtLeastUntil())); logger.debug("Unlocked {}", lockConfiguration); } } @@ -64,8 +64,7 @@ private Optional doExtend(LockConfiguration newConfiguration) { } } - private record LockRecord(Instant lockedUntil) { - } + private record LockRecord(Instant lockedUntil) {} private class InMemoryLock extends AbstractSimpleLock { diff --git a/providers/inmemory/shedlock-provider-inmemory/src/test/java/net/javacrumbs/shedlock/provider/inmemory/InMemoryLockProviderIntegrationTest.java b/providers/inmemory/shedlock-provider-inmemory/src/test/java/net/javacrumbs/shedlock/provider/inmemory/InMemoryLockProviderIntegrationTest.java index bdbdfa4f2..7970eceaf 100644 --- a/providers/inmemory/shedlock-provider-inmemory/src/test/java/net/javacrumbs/shedlock/provider/inmemory/InMemoryLockProviderIntegrationTest.java +++ b/providers/inmemory/shedlock-provider-inmemory/src/test/java/net/javacrumbs/shedlock/provider/inmemory/InMemoryLockProviderIntegrationTest.java @@ -1,10 +1,10 @@ package net.javacrumbs.shedlock.provider.inmemory; +import static org.assertj.core.api.Assertions.assertThat; + import net.javacrumbs.shedlock.core.ExtensibleLockProvider; import net.javacrumbs.shedlock.test.support.AbstractExtensibleLockProviderIntegrationTest; -import static org.assertj.core.api.Assertions.assertThat; - public class InMemoryLockProviderIntegrationTest extends AbstractExtensibleLockProviderIntegrationTest { private final InMemoryLockProvider inMemoryLockProvider = new InMemoryLockProvider(); diff --git a/providers/jdbc/shedlock-provider-jdbc-internal/src/main/java/net/javacrumbs/shedlock/provider/jdbc/internal/AbstractJdbcStorageAccessor.java b/providers/jdbc/shedlock-provider-jdbc-internal/src/main/java/net/javacrumbs/shedlock/provider/jdbc/internal/AbstractJdbcStorageAccessor.java index 907f4fe5d..426c3d9c2 100644 --- a/providers/jdbc/shedlock-provider-jdbc-internal/src/main/java/net/javacrumbs/shedlock/provider/jdbc/internal/AbstractJdbcStorageAccessor.java +++ b/providers/jdbc/shedlock-provider-jdbc-internal/src/main/java/net/javacrumbs/shedlock/provider/jdbc/internal/AbstractJdbcStorageAccessor.java @@ -1,37 +1,32 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbc.internal; -import net.javacrumbs.shedlock.core.ClockProvider; -import net.javacrumbs.shedlock.core.LockConfiguration; -import net.javacrumbs.shedlock.support.AbstractStorageAccessor; -import net.javacrumbs.shedlock.support.LockException; -import net.javacrumbs.shedlock.support.annotation.NonNull; +import static java.util.Objects.requireNonNull; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLIntegrityConstraintViolationException; import java.sql.Timestamp; import java.util.function.BiFunction; +import net.javacrumbs.shedlock.core.ClockProvider; +import net.javacrumbs.shedlock.core.LockConfiguration; +import net.javacrumbs.shedlock.support.AbstractStorageAccessor; +import net.javacrumbs.shedlock.support.LockException; +import net.javacrumbs.shedlock.support.annotation.NonNull; -import static java.util.Objects.requireNonNull; - -/** - * Internal class, please do not use. - */ +/** Internal class, please do not use. */ public abstract class AbstractJdbcStorageAccessor extends AbstractStorageAccessor { private final String tableName; @@ -41,31 +36,40 @@ public AbstractJdbcStorageAccessor(@NonNull String tableName) { @Override public boolean insertRecord(@NonNull LockConfiguration lockConfiguration) { - // Try to insert if the record does not exist (not optimal, but the simplest platform agnostic way) + // Try to insert if the record does not exist (not optimal, but the simplest + // platform agnostic + // way) String sql = "INSERT INTO " + tableName + "(name, lock_until, locked_at, locked_by) VALUES(?, ?, ?, ?)"; - return executeCommand(sql, statement -> { - statement.setString(1, lockConfiguration.getName()); - statement.setTimestamp(2, Timestamp.from(lockConfiguration.getLockAtMostUntil())); - statement.setTimestamp(3, Timestamp.from(ClockProvider.now())); - statement.setString(4, getHostname()); - int insertedRows = statement.executeUpdate(); - return insertedRows > 0; - }, this::handleInsertionException); + return executeCommand( + sql, + statement -> { + statement.setString(1, lockConfiguration.getName()); + statement.setTimestamp(2, Timestamp.from(lockConfiguration.getLockAtMostUntil())); + statement.setTimestamp(3, Timestamp.from(ClockProvider.now())); + statement.setString(4, getHostname()); + int insertedRows = statement.executeUpdate(); + return insertedRows > 0; + }, + this::handleInsertionException); } @Override public boolean updateRecord(@NonNull LockConfiguration lockConfiguration) { - String sql = "UPDATE " + tableName + " SET lock_until = ?, locked_at = ?, locked_by = ? WHERE name = ? AND lock_until <= ?"; - return executeCommand(sql, statement -> { - Timestamp now = Timestamp.from(ClockProvider.now()); - statement.setTimestamp(1, Timestamp.from(lockConfiguration.getLockAtMostUntil())); - statement.setTimestamp(2, now); - statement.setString(3, getHostname()); - statement.setString(4, lockConfiguration.getName()); - statement.setTimestamp(5, now); - int updatedRows = statement.executeUpdate(); - return updatedRows > 0; - }, this::handleUpdateException); + String sql = "UPDATE " + tableName + + " SET lock_until = ?, locked_at = ?, locked_by = ? WHERE name = ? AND lock_until <= ?"; + return executeCommand( + sql, + statement -> { + Timestamp now = Timestamp.from(ClockProvider.now()); + statement.setTimestamp(1, Timestamp.from(lockConfiguration.getLockAtMostUntil())); + statement.setTimestamp(2, now); + statement.setString(3, getHostname()); + statement.setString(4, lockConfiguration.getName()); + statement.setTimestamp(5, now); + int updatedRows = statement.executeUpdate(); + return updatedRows > 0; + }, + this::handleUpdateException); } @Override @@ -74,38 +78,44 @@ public boolean extend(@NonNull LockConfiguration lockConfiguration) { logger.debug("Extending lock={} until={}", lockConfiguration.getName(), lockConfiguration.getLockAtMostUntil()); - return executeCommand(sql, statement -> { - statement.setTimestamp(1, Timestamp.from(lockConfiguration.getLockAtMostUntil())); - statement.setString(2, lockConfiguration.getName()); - statement.setString(3, getHostname()); - statement.setTimestamp(4, Timestamp.from(ClockProvider.now())); - return statement.executeUpdate() > 0; - }, this::handleUnlockException); + return executeCommand( + sql, + statement -> { + statement.setTimestamp(1, Timestamp.from(lockConfiguration.getLockAtMostUntil())); + statement.setString(2, lockConfiguration.getName()); + statement.setString(3, getHostname()); + statement.setTimestamp(4, Timestamp.from(ClockProvider.now())); + return statement.executeUpdate() > 0; + }, + this::handleUnlockException); } @Override public void unlock(@NonNull LockConfiguration lockConfiguration) { String sql = "UPDATE " + tableName + " SET lock_until = ? WHERE name = ?"; - executeCommand(sql, statement -> { - statement.setTimestamp(1, Timestamp.from(lockConfiguration.getUnlockTime())); - statement.setString(2, lockConfiguration.getName()); - statement.executeUpdate(); - return null; - }, this::handleUnlockException); + executeCommand( + sql, + statement -> { + statement.setTimestamp(1, Timestamp.from(lockConfiguration.getUnlockTime())); + statement.setString(2, lockConfiguration.getName()); + statement.executeUpdate(); + return null; + }, + this::handleUnlockException); } protected abstract T executeCommand( - String sql, - SqlFunction body, - BiFunction exceptionHandler - ); + String sql, SqlFunction body, BiFunction exceptionHandler); boolean handleInsertionException(String sql, SQLException e) { if (e instanceof SQLIntegrityConstraintViolationException) { // lock record already exists } else { - // can not throw exception here, some drivers (Postgres) do not throw SQLIntegrityConstraintViolationException on duplicate key - // we will try update in the next step, so if there is another problem, an exception will be thrown there + // can not throw exception here, some drivers (Postgres) do not throw + // SQLIntegrityConstraintViolationException on duplicate key + // we will try update in the next step, so if there is another problem, an + // exception will be + // thrown there logger.debug("Exception thrown when inserting record", e); } return false; @@ -125,4 +135,3 @@ public interface SqlFunction { R apply(T t) throws SQLException; } } - diff --git a/providers/jdbc/shedlock-provider-jdbc-micronaut/src/main/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/MicronautJdbcLockProvider.java b/providers/jdbc/shedlock-provider-jdbc-micronaut/src/main/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/MicronautJdbcLockProvider.java index f9c362ae9..1393b0c41 100644 --- a/providers/jdbc/shedlock-provider-jdbc-micronaut/src/main/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/MicronautJdbcLockProvider.java +++ b/providers/jdbc/shedlock-provider-jdbc-micronaut/src/main/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/MicronautJdbcLockProvider.java @@ -1,48 +1,40 @@ /** * Copyright 2009-2021 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbc.micronaut; import io.micronaut.transaction.TransactionOperations; import io.micronaut.transaction.jdbc.DataSourceTransactionManager; +import java.sql.Connection; +import javax.sql.DataSource; import net.javacrumbs.shedlock.support.StorageBasedLockProvider; import net.javacrumbs.shedlock.support.annotation.NonNull; -import javax.sql.DataSource; -import java.sql.Connection; - /** - * Lock provided by plain JDBC, using the Micronaut Data transaction manager. It uses a table that contains lock_name and locked_until. + * Lock provided by plain JDBC, using the Micronaut Data transaction manager. It + * uses a table that contains lock_name and locked_until. + * *

    - *
  1. - * Attempts to insert a new lock record. Since lock name is a primary key, it fails if the record already exists. As an optimization, - * we keep in-memory track of created lock records. - *
  2. - *
  3. - * If the insert succeeds (1 inserted row) we have the lock. - *
  4. - *
  5. - * If the insert failed due to duplicate key or we have skipped the insertion, we will try to update lock record using - * UPDATE tableName SET lock_until = :lockUntil WHERE name = :lockName AND lock_until <= :now - *
  6. - *
  7. - * If the update succeeded (1 updated row), we have the lock. If the update failed (0 updated rows) somebody else holds the lock - *
  8. - *
  9. - * When unlocking, lock_until is set to now. - *
  10. + *
  11. Attempts to insert a new lock record. Since lock name is a primary key, + * it fails if the record already exists. As an optimization, we keep in-memory + * track of created lock records. + *
  12. If the insert succeeds (1 inserted row) we have the lock. + *
  13. If the insert failed due to duplicate key or we have skipped the + * insertion, we will try to update lock record using UPDATE tableName SET + * lock_until = :lockUntil WHERE name = :lockName AND lock_until <= :now + *
  14. If the update succeeded (1 updated row), we have the lock. If the update + * failed (0 updated rows) somebody else holds the lock + *
  15. When unlocking, lock_until is set to now. *
*/ public class MicronautJdbcLockProvider extends StorageBasedLockProvider { @@ -50,10 +42,10 @@ public class MicronautJdbcLockProvider extends StorageBasedLockProvider { private static final String DEFAULT_TABLE_NAME = "shedlock"; /** - * - * @deprecated Use {@link #MicronautJdbcLockProvider(TransactionOperations)} instead as - * transaction management has be refactored in Micronaut Data 4.0 and DataSourceTransactionManager - * is not easy to construct. + * @deprecated Use {@link #MicronautJdbcLockProvider(TransactionOperations)} + * instead as transaction management has be refactored in Micronaut + * Data 4.0 and DataSourceTransactionManager is not easy to + * construct. */ @Deprecated public MicronautJdbcLockProvider(@NonNull DataSource datasource) { @@ -64,7 +56,8 @@ public MicronautJdbcLockProvider(@NonNull TransactionOperations tran this(transactionManager, DEFAULT_TABLE_NAME); } - public MicronautJdbcLockProvider(@NonNull TransactionOperations transactionManager, @NonNull String tableName) { + public MicronautJdbcLockProvider( + @NonNull TransactionOperations transactionManager, @NonNull String tableName) { super(new MicronautJdbcStorageAccessor(transactionManager, tableName)); } } diff --git a/providers/jdbc/shedlock-provider-jdbc-micronaut/src/main/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/MicronautJdbcStorageAccessor.java b/providers/jdbc/shedlock-provider-jdbc-micronaut/src/main/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/MicronautJdbcStorageAccessor.java index 5745856a6..8201c6752 100644 --- a/providers/jdbc/shedlock-provider-jdbc-micronaut/src/main/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/MicronautJdbcStorageAccessor.java +++ b/providers/jdbc/shedlock-provider-jdbc-micronaut/src/main/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/MicronautJdbcStorageAccessor.java @@ -1,44 +1,43 @@ /** * Copyright 2009-2021 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbc.micronaut; +import static java.util.Objects.requireNonNull; + import io.micronaut.transaction.TransactionDefinition; import io.micronaut.transaction.TransactionOperations; -import net.javacrumbs.shedlock.provider.jdbc.internal.AbstractJdbcStorageAccessor; -import net.javacrumbs.shedlock.support.annotation.NonNull; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.function.BiFunction; - -import static java.util.Objects.requireNonNull; +import net.javacrumbs.shedlock.provider.jdbc.internal.AbstractJdbcStorageAccessor; +import net.javacrumbs.shedlock.support.annotation.NonNull; class MicronautJdbcStorageAccessor extends AbstractJdbcStorageAccessor { private final TransactionOperations transactionManager; private final TransactionDefinition.Propagation propagation = TransactionDefinition.Propagation.REQUIRES_NEW; - MicronautJdbcStorageAccessor(@NonNull TransactionOperations transactionManager, @NonNull String tableName) { + MicronautJdbcStorageAccessor( + @NonNull TransactionOperations transactionManager, @NonNull String tableName) { super(tableName); this.transactionManager = requireNonNull(transactionManager, "transactionManager can not be null"); } @Override - protected T executeCommand(String sql, SqlFunction body, BiFunction exceptionHandler) { + protected T executeCommand( + String sql, SqlFunction body, BiFunction exceptionHandler) { return transactionManager.execute(TransactionDefinition.of(propagation), status -> { try (PreparedStatement statement = status.getConnection().prepareStatement(sql)) { return body.apply(statement); diff --git a/providers/jdbc/shedlock-provider-jdbc-micronaut/src/test/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/HsqlJdbcLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc-micronaut/src/test/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/HsqlJdbcLockProviderIntegrationTest.java index 57f73611f..c95a542ff 100644 --- a/providers/jdbc/shedlock-provider-jdbc-micronaut/src/test/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/HsqlJdbcLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-micronaut/src/test/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/HsqlJdbcLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009-2021 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbc.micronaut; diff --git a/providers/jdbc/shedlock-provider-jdbc-micronaut/src/test/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/MySqlJdbcLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc-micronaut/src/test/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/MySqlJdbcLockProviderIntegrationTest.java index 67d845131..9db0944ab 100644 --- a/providers/jdbc/shedlock-provider-jdbc-micronaut/src/test/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/MySqlJdbcLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-micronaut/src/test/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/MySqlJdbcLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009-2021 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbc.micronaut; diff --git a/providers/jdbc/shedlock-provider-jdbc-micronaut/src/test/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/PostgresJdbcLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc-micronaut/src/test/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/PostgresJdbcLockProviderIntegrationTest.java index 2abb2b515..25273a770 100644 --- a/providers/jdbc/shedlock-provider-jdbc-micronaut/src/test/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/PostgresJdbcLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-micronaut/src/test/java/net/javacrumbs/shedlock/provider/jdbc/micronaut/PostgresJdbcLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009-2021 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbc.micronaut; diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/DatabaseProduct.java b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/DatabaseProduct.java index dc281c16b..1058750ce 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/DatabaseProduct.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/DatabaseProduct.java @@ -1,11 +1,10 @@ package net.javacrumbs.shedlock.provider.jdbctemplate; -import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration; -import net.javacrumbs.shedlock.support.annotation.NonNull; - import java.util.Arrays; import java.util.function.Function; import java.util.function.Predicate; +import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration; +import net.javacrumbs.shedlock.support.annotation.NonNull; public enum DatabaseProduct { POSTGRES_SQL("PostgreSQL"::equals, PostgresSqlServerTimeStatementsSource::new), @@ -24,7 +23,8 @@ public enum DatabaseProduct { private final Function serverTimeStatementsSource; - DatabaseProduct(Predicate productMatcher, Function serverTimeStatementsSource) { + DatabaseProduct( + Predicate productMatcher, Function serverTimeStatementsSource) { this.productMatcher = productMatcher; this.serverTimeStatementsSource = serverTimeStatementsSource; } @@ -34,16 +34,19 @@ SqlStatementsSource getDbTimeStatementSource(Configuration configuration) { } /** - * Searches for the right DatabaseProduct based on the ProductName returned from JDBC Connection Metadata + * Searches for the right DatabaseProduct based on the ProductName returned from + * JDBC Connection Metadata * - * @param productName Obtained from the JDBC connection. See java.sql.connection.getMetaData().getProductName(). + * @param productName + * Obtained from the JDBC connection. See + * java.sql.connection.getMetaData().getProductName(). * @return The matching ProductName enum */ @NonNull static DatabaseProduct matchProductName(final String productName) { return Arrays.stream(DatabaseProduct.values()) - .filter(databaseProduct -> databaseProduct.productMatcher.test(productName)) - .findFirst().orElse(UNKNOWN); + .filter(databaseProduct -> databaseProduct.productMatcher.test(productName)) + .findFirst() + .orElse(UNKNOWN); } } - diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/Db2ServerTimeStatementsSource.java b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/Db2ServerTimeStatementsSource.java index 435a948da..9ac4feac4 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/Db2ServerTimeStatementsSource.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/Db2ServerTimeStatementsSource.java @@ -1,28 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; +import java.util.Map; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.support.annotation.NonNull; -import java.util.Map; - class Db2ServerTimeStatementsSource extends SqlStatementsSource { private static final String now = "(CURRENT TIMESTAMP - CURRENT TIMEZONE)"; - private static final String lockAtMostFor = "("+ now + " + :lockAtMostForMicros MICROSECONDS)"; + private static final String lockAtMostFor = "(" + now + " + :lockAtMostForMicros MICROSECONDS)"; Db2ServerTimeStatementsSource(JdbcTemplateLockProvider.Configuration configuration) { super(configuration); @@ -30,33 +27,41 @@ class Db2ServerTimeStatementsSource extends SqlStatementsSource { @Override String getInsertStatement() { - return "INSERT INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)"; + return "INSERT INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)"; } @Override public String getUpdateStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now; } @Override public String getUnlockStatement() { String lockAtLeastFor = "(" + lockedAt() + "+ :lockAtLeastForMicros MICROSECONDS)"; - return "UPDATE " + tableName() + " SET " + lockUntil() + " = CASE WHEN " + lockAtLeastFor + " > " + now + " THEN " + lockAtLeastFor + " ELSE " + now + " END WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy"; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = CASE WHEN " + lockAtLeastFor + " > " + now + + " THEN " + lockAtLeastFor + " ELSE " + now + " END WHERE " + name() + " = :name AND " + lockedBy() + + " = :lockedBy"; } @Override public String getExtendStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; } @Override @NonNull Map params(@NonNull LockConfiguration lockConfiguration) { return Map.of( - "name", lockConfiguration.getName(), - "lockedBy", configuration.getLockedByValue(), - "lockAtMostForMicros", lockConfiguration.getLockAtMostFor().toNanos() / 1_000, - "lockAtLeastForMicros", lockConfiguration.getLockAtLeastFor().toNanos() / 1_000 - ); + "name", + lockConfiguration.getName(), + "lockedBy", + configuration.getLockedByValue(), + "lockAtMostForMicros", + lockConfiguration.getLockAtMostFor().toNanos() / 1_000, + "lockAtLeastForMicros", + lockConfiguration.getLockAtLeastFor().toNanos() / 1_000); } } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/H2ServerTimeStatementsSource.java b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/H2ServerTimeStatementsSource.java index 21cdeeb6a..1d814bb85 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/H2ServerTimeStatementsSource.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/H2ServerTimeStatementsSource.java @@ -1,25 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; +import java.util.Map; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.support.annotation.NonNull; -import java.util.Map; - class H2ServerTimeStatementsSource extends SqlStatementsSource { private static final String now = "CURRENT_TIMESTAMP(3)"; private static final String lockAtMostFor = "TIMESTAMPADD(MICROSECOND, :lockAtMostForMicros, " + now + ")"; @@ -30,33 +27,41 @@ class H2ServerTimeStatementsSource extends SqlStatementsSource { @Override String getInsertStatement() { - return "INSERT INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)"; + return "INSERT INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)"; } @Override public String getUpdateStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now; } @Override public String getUnlockStatement() { String lockAtLeastFor = "TIMESTAMPADD(MICROSECOND, :lockAtLeastForMicros, " + lockedAt() + ")"; - return "UPDATE " + tableName() + " SET " + lockUntil() + " = CASE WHEN " + lockAtLeastFor + " > " + now + " THEN " + lockAtLeastFor + " ELSE " + now + " END WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy"; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = CASE WHEN " + lockAtLeastFor + " > " + now + + " THEN " + lockAtLeastFor + " ELSE " + now + " END WHERE " + name() + " = :name AND " + lockedBy() + + " = :lockedBy"; } @Override public String getExtendStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; } @Override @NonNull Map params(@NonNull LockConfiguration lockConfiguration) { return Map.of( - "name", lockConfiguration.getName(), - "lockedBy", configuration.getLockedByValue(), - "lockAtMostForMicros", lockConfiguration.getLockAtMostFor().toNanos() / 1_000, - "lockAtLeastForMicros", lockConfiguration.getLockAtLeastFor().toNanos() / 1_000 - ); + "name", + lockConfiguration.getName(), + "lockedBy", + configuration.getLockedByValue(), + "lockAtMostForMicros", + lockConfiguration.getLockAtMostFor().toNanos() / 1_000, + "lockAtLeastForMicros", + lockConfiguration.getLockAtLeastFor().toNanos() / 1_000); } } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/HsqlServerTimeStatementsSource.java b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/HsqlServerTimeStatementsSource.java index 34c2294d6..e83d98c5f 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/HsqlServerTimeStatementsSource.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/HsqlServerTimeStatementsSource.java @@ -1,25 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; +import java.util.Map; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.support.annotation.NonNull; -import java.util.Map; - class HsqlServerTimeStatementsSource extends SqlStatementsSource { private static final String now = "CURRENT_TIMESTAMP(3)"; private static final String lockAtMostFor = "TIMESTAMPADD(MICROSECOND, :lockAtMostForMicros, " + now + ")"; @@ -30,33 +27,41 @@ class HsqlServerTimeStatementsSource extends SqlStatementsSource { @Override String getInsertStatement() { - return "INSERT INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)"; + return "INSERT INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)"; } @Override public String getUpdateStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now; } @Override public String getUnlockStatement() { String lockAtLeastFor = "TIMESTAMPADD(MICROSECOND, :lockAtLeastForMicros, " + lockedAt() + ")"; - return "UPDATE " + tableName() + " SET " + lockUntil() + " = CASE WHEN " + lockAtLeastFor + " > " + now + " THEN " + lockAtLeastFor + " ELSE " + now + " END WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy"; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = CASE WHEN " + lockAtLeastFor + " > " + now + + " THEN " + lockAtLeastFor + " ELSE " + now + " END WHERE " + name() + " = :name AND " + lockedBy() + + " = :lockedBy"; } @Override public String getExtendStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; } @Override @NonNull Map params(@NonNull LockConfiguration lockConfiguration) { return Map.of( - "name", lockConfiguration.getName(), - "lockedBy", configuration.getLockedByValue(), - "lockAtMostForMicros", lockConfiguration.getLockAtMostFor().toNanos() / 1_000, - "lockAtLeastForMicros", lockConfiguration.getLockAtLeastFor().toNanos() / 1_000 - ); + "name", + lockConfiguration.getName(), + "lockedBy", + configuration.getLockedByValue(), + "lockAtMostForMicros", + lockConfiguration.getLockAtMostFor().toNanos() / 1_000, + "lockAtLeastForMicros", + lockConfiguration.getLockAtLeastFor().toNanos() / 1_000); } } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateLockProvider.java b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateLockProvider.java index 697784ceb..21598fea5 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateLockProvider.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateLockProvider.java @@ -1,20 +1,22 @@ /** * Copyright 2009 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + * + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + *

http://www.apache.org/licenses/LICENSE-2.0 + * + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; +import static java.util.Objects.requireNonNull; + +import java.util.TimeZone; +import javax.sql.DataSource; import net.javacrumbs.shedlock.support.StorageBasedLockProvider; import net.javacrumbs.shedlock.support.Utils; import net.javacrumbs.shedlock.support.annotation.NonNull; @@ -22,31 +24,21 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.PlatformTransactionManager; -import javax.sql.DataSource; -import java.util.TimeZone; - -import static java.util.Objects.requireNonNull; - /** - * Lock provided by JdbcTemplate. It uses a table that contains lock_name and locked_until. + * Lock provided by JdbcTemplate. It uses a table that contains lock_name and + * locked_until. + * *

    - *
  1. - * Attempts to insert a new lock record. Since lock name is a primary key, it fails if the record already exists. As an optimization, - * we keep in-memory track of created lock records. - *
  2. - *
  3. - * If the insert succeeds (1 inserted row) we have the lock. - *
  4. - *
  5. - * If the insert failed due to duplicate key or we have skipped the insertion, we will try to update lock record using - * UPDATE tableName SET lock_until = :lockUntil WHERE name = :lockName AND lock_until <= :now - *
  6. - *
  7. - * If the update succeeded (1 updated row), we have the lock. If the update failed (0 updated rows) somebody else holds the lock - *
  8. - *
  9. - * When unlocking, lock_until is set to now. - *
  10. + *
  11. Attempts to insert a new lock record. Since lock name is a primary key, + * it fails if the record already exists. As an optimization, we keep in-memory + * track of created lock records. + *
  12. If the insert succeeds (1 inserted row) we have the lock. + *
  13. If the insert failed due to duplicate key or we have skipped the + * insertion, we will try to update lock record using UPDATE tableName SET + * lock_until = :lockUntil WHERE name = :lockName AND lock_until <= :now + *
  14. If the update succeeded (1 updated row), we have the lock. If the update + * failed (0 updated rows) somebody else holds the lock + *
  15. When unlocking, lock_until is set to now. *
*/ public class JdbcTemplateLockProvider extends StorageBasedLockProvider { @@ -57,7 +49,8 @@ public JdbcTemplateLockProvider(@NonNull JdbcTemplate jdbcTemplate) { this(jdbcTemplate, (PlatformTransactionManager) null); } - public JdbcTemplateLockProvider(@NonNull JdbcTemplate jdbcTemplate, @Nullable PlatformTransactionManager transactionManager) { + public JdbcTemplateLockProvider( + @NonNull JdbcTemplate jdbcTemplate, @Nullable PlatformTransactionManager transactionManager) { this(jdbcTemplate, transactionManager, DEFAULT_TABLE_NAME); } @@ -73,13 +66,15 @@ public JdbcTemplateLockProvider(@NonNull DataSource dataSource, @NonNull String this(new JdbcTemplate(dataSource), tableName); } - public JdbcTemplateLockProvider(@NonNull JdbcTemplate jdbcTemplate, @Nullable PlatformTransactionManager transactionManager, @NonNull String tableName) { + public JdbcTemplateLockProvider( + @NonNull JdbcTemplate jdbcTemplate, + @Nullable PlatformTransactionManager transactionManager, + @NonNull String tableName) { this(Configuration.builder() - .withJdbcTemplate(jdbcTemplate) - .withTransactionManager(transactionManager) - .withTableName(tableName) - .build() - ); + .withJdbcTemplate(jdbcTemplate) + .withTransactionManager(transactionManager) + .withTableName(tableName) + .build()); } public JdbcTemplateLockProvider(@NonNull Configuration configuration) { @@ -98,15 +93,15 @@ public static final class Configuration { private final Integer isolationLevel; Configuration( - @NonNull JdbcTemplate jdbcTemplate, - @Nullable DatabaseProduct databaseProduct, - @Nullable PlatformTransactionManager transactionManager, - @NonNull String tableName, - @Nullable TimeZone timeZone, - @NonNull ColumnNames columnNames, - @NonNull String lockedByValue, - boolean useDbTime, - @Nullable Integer isolationLevel) { + @NonNull JdbcTemplate jdbcTemplate, + @Nullable DatabaseProduct databaseProduct, + @Nullable PlatformTransactionManager transactionManager, + @NonNull String tableName, + @Nullable TimeZone timeZone, + @NonNull ColumnNames columnNames, + @NonNull String lockedByValue, + boolean useDbTime, + @Nullable Integer isolationLevel) { this.jdbcTemplate = requireNonNull(jdbcTemplate, "jdbcTemplate can not be null"); this.databaseProduct = databaseProduct; @@ -162,7 +157,6 @@ public static Configuration.Builder builder() { return new Configuration.Builder(); } - public static final class Builder { private JdbcTemplate jdbcTemplate; private DatabaseProduct databaseProduct; @@ -207,7 +201,9 @@ public Builder withDbUpperCase(final boolean dbUpperCase) { /** * This is only needed if your database product can't be automatically detected. - * @param databaseProduct Database product + * + * @param databaseProduct + * Database product * @return ConfigurationBuilder */ public Builder withDatabaseProduct(final DatabaseProduct databaseProduct) { @@ -215,7 +211,6 @@ public Builder withDatabaseProduct(final DatabaseProduct databaseProduct) { return this; } - /** * Value stored in 'locked_by' column. Please use only for debugging purposes. */ @@ -230,8 +225,8 @@ public Builder usingDbTime() { } /** - * Sets the isolation level for ShedLock. See {@link java.sql.Connection} for constant definitions. - * for constant definitions + * Sets the isolation level for ShedLock. See {@link java.sql.Connection} for + * constant definitions. for constant definitions */ public Builder withIsolationLevel(int isolationLevel) { this.isolationLevel = isolationLevel; @@ -240,16 +235,15 @@ public Builder withIsolationLevel(int isolationLevel) { public JdbcTemplateLockProvider.Configuration build() { return new JdbcTemplateLockProvider.Configuration( - jdbcTemplate, - databaseProduct, - transactionManager, - dbUpperCase ? tableName.toUpperCase() : tableName, - timeZone, - dbUpperCase ? columnNames.toUpperCase() : columnNames, - lockedByValue, - useDbTime, - isolationLevel - ); + jdbcTemplate, + databaseProduct, + transactionManager, + dbUpperCase ? tableName.toUpperCase() : tableName, + timeZone, + dbUpperCase ? columnNames.toUpperCase() : columnNames, + lockedByValue, + useDbTime, + isolationLevel); } } } @@ -285,12 +279,7 @@ public String getLockedBy() { private ColumnNames toUpperCase() { return new ColumnNames( - name.toUpperCase(), - lockUntil.toUpperCase(), - lockedAt.toUpperCase(), - lockedBy.toUpperCase() - ); + name.toUpperCase(), lockUntil.toUpperCase(), lockedAt.toUpperCase(), lockedBy.toUpperCase()); } } - } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateStorageAccessor.java b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateStorageAccessor.java index 130144b8a..c3bd407ed 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateStorageAccessor.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateStorageAccessor.java @@ -1,20 +1,21 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; +import static java.util.Objects.requireNonNull; + +import java.util.Map; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration; import net.javacrumbs.shedlock.support.AbstractStorageAccessor; @@ -32,13 +33,7 @@ import org.springframework.transaction.TransactionSystemException; import org.springframework.transaction.support.TransactionTemplate; -import java.util.Map; - -import static java.util.Objects.requireNonNull; - -/** - * Spring JdbcTemplate based implementation usable in JTA environment - */ +/** Spring JdbcTemplate based implementation usable in JTA environment */ class JdbcTemplateStorageAccessor extends AbstractStorageAccessor { private final NamedParameterJdbcTemplate jdbcTemplate; private final TransactionTemplate transactionTemplate; @@ -49,9 +44,10 @@ class JdbcTemplateStorageAccessor extends AbstractStorageAccessor { requireNonNull(configuration, "configuration can not be null"); this.jdbcTemplate = new NamedParameterJdbcTemplate(configuration.getJdbcTemplate()); this.configuration = configuration; - PlatformTransactionManager transactionManager = configuration.getTransactionManager() != null ? - configuration.getTransactionManager() : - new DataSourceTransactionManager(configuration.getJdbcTemplate().getDataSource()); + PlatformTransactionManager transactionManager = configuration.getTransactionManager() != null + ? configuration.getTransactionManager() + : new DataSourceTransactionManager( + configuration.getJdbcTemplate().getDataSource()); this.transactionTemplate = new TransactionTemplate(transactionManager); this.transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/MsSqlServerTimeStatementsSource.java b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/MsSqlServerTimeStatementsSource.java index 0dc1099e4..eb39b7ff2 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/MsSqlServerTimeStatementsSource.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/MsSqlServerTimeStatementsSource.java @@ -1,25 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; +import java.util.Map; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.support.annotation.NonNull; -import java.util.Map; - class MsSqlServerTimeStatementsSource extends SqlStatementsSource { private static final String now = "SYSUTCDATETIME()"; private static final String lockAtMostFor = "DATEADD(millisecond, :lockAtMostForMillis, " + now + ")"; @@ -30,32 +27,41 @@ class MsSqlServerTimeStatementsSource extends SqlStatementsSource { @Override String getInsertStatement() { - return "INSERT INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)"; + return "INSERT INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)"; } @Override public String getUpdateStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now; } @Override public String getUnlockStatement() { String lockAtLeastFor = "DATEADD(millisecond, :lockAtLeastForMillis, " + lockedAt() + ")"; - return "UPDATE " + tableName() + " SET " + lockUntil() + " = CASE WHEN " + lockAtLeastFor + " > " + now + " THEN " + lockAtLeastFor + " ELSE " + now + " END WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy"; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = CASE WHEN " + lockAtLeastFor + " > " + now + + " THEN " + lockAtLeastFor + " ELSE " + now + " END WHERE " + name() + " = :name AND " + lockedBy() + + " = :lockedBy"; } @Override public String getExtendStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; } @Override - @NonNull Map params(@NonNull LockConfiguration lockConfiguration) { + @NonNull + Map params(@NonNull LockConfiguration lockConfiguration) { return Map.of( - "name", lockConfiguration.getName(), - "lockedBy", configuration.getLockedByValue(), - "lockAtMostForMillis", lockConfiguration.getLockAtMostFor().toMillis(), - "lockAtLeastForMillis", lockConfiguration.getLockAtLeastFor().toMillis() - ); + "name", + lockConfiguration.getName(), + "lockedBy", + configuration.getLockedByValue(), + "lockAtMostForMillis", + lockConfiguration.getLockAtMostFor().toMillis(), + "lockAtLeastForMillis", + lockConfiguration.getLockAtLeastFor().toMillis()); } } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/MySqlServerTimeStatementsSource.java b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/MySqlServerTimeStatementsSource.java index 0ceeba21c..c21c5d025 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/MySqlServerTimeStatementsSource.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/MySqlServerTimeStatementsSource.java @@ -1,25 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; +import java.util.Map; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.support.annotation.NonNull; -import java.util.Map; - class MySqlServerTimeStatementsSource extends SqlStatementsSource { private static final String now = "UTC_TIMESTAMP(3)"; private static final String lockAtMostFor = "TIMESTAMPADD(MICROSECOND, :lockAtMostForMicros, " + now + ")"; @@ -30,32 +27,40 @@ class MySqlServerTimeStatementsSource extends SqlStatementsSource { @Override String getInsertStatement() { - return "INSERT IGNORE INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)"; + return "INSERT IGNORE INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + + lockedBy() + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)"; } @Override public String getUpdateStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now; } @Override public String getUnlockStatement() { String lockAtLeastFor = "TIMESTAMPADD(MICROSECOND, :lockAtLeastForMicros, " + lockedAt() + ")"; - return "UPDATE " + tableName() + " SET " + lockUntil() + " = IF (" + lockAtLeastFor + " > " + now + " , " + lockAtLeastFor + ", " + now + ") WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy"; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = IF (" + lockAtLeastFor + " > " + now + " , " + + lockAtLeastFor + ", " + now + ") WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy"; } @Override public String getExtendStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; } @Override - @NonNull Map params(@NonNull LockConfiguration lockConfiguration) { + @NonNull + Map params(@NonNull LockConfiguration lockConfiguration) { return Map.of( - "name", lockConfiguration.getName(), - "lockedBy", configuration.getLockedByValue(), - "lockAtMostForMicros", lockConfiguration.getLockAtMostFor().toNanos() / 1_000, - "lockAtLeastForMicros", lockConfiguration.getLockAtLeastFor().toNanos() / 1_000 - ); + "name", + lockConfiguration.getName(), + "lockedBy", + configuration.getLockedByValue(), + "lockAtMostForMicros", + lockConfiguration.getLockAtMostFor().toNanos() / 1_000, + "lockAtLeastForMicros", + lockConfiguration.getLockAtLeastFor().toNanos() / 1_000); } } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/OracleServerTimeStatementsSource.java b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/OracleServerTimeStatementsSource.java index 4a8ac384d..e3050077a 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/OracleServerTimeStatementsSource.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/OracleServerTimeStatementsSource.java @@ -1,25 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; +import java.util.Map; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.support.annotation.NonNull; -import java.util.Map; - class OracleServerTimeStatementsSource extends SqlStatementsSource { private static final String now = "SYS_EXTRACT_UTC(SYSTIMESTAMP)"; private static final String lockAtMostFor = now + " + :lockAtMostFor"; @@ -32,33 +29,44 @@ class OracleServerTimeStatementsSource extends SqlStatementsSource { @Override String getInsertStatement() { - return "MERGE INTO " + tableName() + " USING (SELECT 1 FROM dual) ON (" + name() + " = :name) WHEN MATCHED THEN UPDATE SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now + " WHEN NOT MATCHED THEN INSERT(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)"; + return "MERGE INTO " + tableName() + " USING (SELECT 1 FROM dual) ON (" + name() + + " = :name) WHEN MATCHED THEN UPDATE SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + + " = " + now + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + + " <= " + now + " WHEN NOT MATCHED THEN INSERT(" + name() + ", " + lockUntil() + ", " + lockedAt() + + ", " + lockedBy() + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)"; } @Override public String getUpdateStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + + ", " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= " + now; } @Override public String getUnlockStatement() { String lockAtLeastFor = lockedAt() + " + :lockAtLeastFor"; - return "UPDATE " + tableName() + " SET " + lockUntil() + " = CASE WHEN " + lockAtLeastFor + " > " + now + " THEN " + lockAtLeastFor + " ELSE " + now + " END WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy"; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = CASE WHEN " + lockAtLeastFor + " > " + now + + " THEN " + lockAtLeastFor + " ELSE " + now + " END WHERE " + name() + " = :name AND " + lockedBy() + + " = :lockedBy"; } @Override public String getExtendStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; } @Override @NonNull Map params(@NonNull LockConfiguration lockConfiguration) { return Map.of( - "name", lockConfiguration.getName(), - "lockedBy", configuration.getLockedByValue(), - "lockAtMostFor", ((double) lockConfiguration.getLockAtMostFor().toMillis()) / millisecondsInDay, - "lockAtLeastFor", ((double) lockConfiguration.getLockAtLeastFor().toMillis()) / millisecondsInDay - ); + "name", + lockConfiguration.getName(), + "lockedBy", + configuration.getLockedByValue(), + "lockAtMostFor", + ((double) lockConfiguration.getLockAtMostFor().toMillis()) / millisecondsInDay, + "lockAtLeastFor", + ((double) lockConfiguration.getLockAtLeastFor().toMillis()) / millisecondsInDay); } } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresSqlServerTimeStatementsSource.java b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresSqlServerTimeStatementsSource.java index 7d9bce405..64f3005e5 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresSqlServerTimeStatementsSource.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresSqlServerTimeStatementsSource.java @@ -1,25 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; +import java.util.Map; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.support.annotation.NonNull; -import java.util.Map; - class PostgresSqlServerTimeStatementsSource extends SqlStatementsSource { private static final String now = "timezone('utc', CURRENT_TIMESTAMP)"; private static final String lockAtMostFor = now + " + cast(:lockAtMostForInterval as interval)"; @@ -30,13 +27,16 @@ class PostgresSqlServerTimeStatementsSource extends SqlStatementsSource { @Override String getInsertStatement() { - return "INSERT INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)" + - " ON CONFLICT (" + name() + ") DO UPDATE" + updateClause(); + return "INSERT INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + + ") VALUES(:name, " + lockAtMostFor + ", " + now + ", :lockedBy)" + " ON CONFLICT (" + name() + + ") DO UPDATE" + updateClause(); } @NonNull private String updateClause() { - return " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + ", " + lockedBy() + " = :lockedBy WHERE " + tableName() + "." + name() + " = :name AND " + tableName() + "." + lockUntil() + " <= " + now; + return " SET " + lockUntil() + " = " + lockAtMostFor + ", " + lockedAt() + " = " + now + ", " + lockedBy() + + " = :lockedBy WHERE " + tableName() + "." + name() + " = :name AND " + tableName() + "." + lockUntil() + + " <= " + now; } @Override @@ -47,21 +47,28 @@ public String getUpdateStatement() { @Override public String getUnlockStatement() { String lockAtLeastFor = lockedAt() + " + cast(:lockAtLeastForInterval as interval)"; - return "UPDATE " + tableName() + " SET " + lockUntil() + " = CASE WHEN " + lockAtLeastFor + " > " + now + " THEN " + lockAtLeastFor + " ELSE " + now + " END WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy"; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = CASE WHEN " + lockAtLeastFor + " > " + now + + " THEN " + lockAtLeastFor + " ELSE " + now + " END WHERE " + name() + " = :name AND " + lockedBy() + + " = :lockedBy"; } @Override public String getExtendStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor +" WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = " + lockAtMostFor + " WHERE " + name() + + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > " + now; } @Override - @NonNull Map params(@NonNull LockConfiguration lockConfiguration) { + @NonNull + Map params(@NonNull LockConfiguration lockConfiguration) { return Map.of( - "name", lockConfiguration.getName(), - "lockedBy", configuration.getLockedByValue(), - "lockAtMostForInterval", lockConfiguration.getLockAtMostFor().toMillis() + " milliseconds", - "lockAtLeastForInterval", lockConfiguration.getLockAtLeastFor().toMillis() + " milliseconds" - ); + "name", + lockConfiguration.getName(), + "lockedBy", + configuration.getLockedByValue(), + "lockAtMostForInterval", + lockConfiguration.getLockAtMostFor().toMillis() + " milliseconds", + "lockAtLeastForInterval", + lockConfiguration.getLockAtLeastFor().toMillis() + " milliseconds"); } } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresSqlStatementsSource.java b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresSqlStatementsSource.java index a03e0893f..c40d44b8b 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresSqlStatementsSource.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresSqlStatementsSource.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; @@ -22,9 +20,8 @@ class PostgresSqlStatementsSource extends SqlStatementsSource { @Override String getInsertStatement() { - return super.getInsertStatement() + " ON CONFLICT (" + name() + ") DO UPDATE " + - "SET " + lockUntil() + " = :lockUntil, " + lockedAt() + " = :now, " + lockedBy() + " = :lockedBy " + - "WHERE " + tableName() + "." + lockUntil() + " <= :now"; + return super.getInsertStatement() + " ON CONFLICT (" + name() + ") DO UPDATE " + "SET " + lockUntil() + + " = :lockUntil, " + lockedAt() + " = :now, " + lockedBy() + " = :lockedBy " + "WHERE " + tableName() + + "." + lockUntil() + " <= :now"; } - } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/SqlStatementsSource.java b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/SqlStatementsSource.java index 1d1de382e..11d6c1862 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/SqlStatementsSource.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/main/java/net/javacrumbs/shedlock/provider/jdbctemplate/SqlStatementsSource.java @@ -1,28 +1,18 @@ /** * Copyright 2009 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + * + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + *

http://www.apache.org/licenses/LICENSE-2.0 + * + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; -import net.javacrumbs.shedlock.core.ClockProvider; -import net.javacrumbs.shedlock.core.LockConfiguration; -import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration; -import net.javacrumbs.shedlock.support.annotation.NonNull; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.jdbc.core.ConnectionCallback; - import java.sql.Timestamp; import java.time.Instant; import java.util.Calendar; @@ -30,6 +20,13 @@ import java.util.Map; import java.util.Objects; import java.util.TimeZone; +import net.javacrumbs.shedlock.core.ClockProvider; +import net.javacrumbs.shedlock.core.LockConfiguration; +import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration; +import net.javacrumbs.shedlock.support.annotation.NonNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jdbc.core.ConnectionCallback; class SqlStatementsSource { protected final Configuration configuration; @@ -63,7 +60,8 @@ private static DatabaseProduct getDatabaseProduct(final Configuration configurat return configuration.getDatabaseProduct(); } try { - String jdbcProductName = configuration.getJdbcTemplate().execute((ConnectionCallback) connection -> connection.getMetaData().getDatabaseProductName()); + String jdbcProductName = configuration.getJdbcTemplate().execute((ConnectionCallback) + connection -> connection.getMetaData().getDatabaseProductName()); return DatabaseProduct.matchProductName(jdbcProductName); } catch (Exception e) { logger.debug("Can not determine database product name " + e.getMessage()); @@ -74,12 +72,16 @@ private static DatabaseProduct getDatabaseProduct(final Configuration configurat @NonNull Map params(@NonNull LockConfiguration lockConfiguration) { return Map.of( - "name", lockConfiguration.getName(), - "lockUntil", timestamp(lockConfiguration.getLockAtMostUntil()), - "now", timestamp(ClockProvider.now()), - "lockedBy", configuration.getLockedByValue(), - "unlockTime", timestamp(lockConfiguration.getUnlockTime()) - ); + "name", + lockConfiguration.getName(), + "lockUntil", + timestamp(lockConfiguration.getLockAtMostUntil()), + "now", + timestamp(ClockProvider.now()), + "lockedBy", + configuration.getLockedByValue(), + "unlockTime", + timestamp(lockConfiguration.getUnlockTime())); } @NonNull @@ -95,18 +97,19 @@ private Object timestamp(Instant time) { } } - String getInsertStatement() { - return "INSERT INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + ") VALUES(:name, :lockUntil, :now, :lockedBy)"; + return "INSERT INTO " + tableName() + "(" + name() + ", " + lockUntil() + ", " + lockedAt() + ", " + lockedBy() + + ") VALUES(:name, :lockUntil, :now, :lockedBy)"; } - public String getUpdateStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = :lockUntil, " + lockedAt() + " = :now, " + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= :now"; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = :lockUntil, " + lockedAt() + " = :now, " + + lockedBy() + " = :lockedBy WHERE " + name() + " = :name AND " + lockUntil() + " <= :now"; } public String getExtendStatement() { - return "UPDATE " + tableName() + " SET " + lockUntil() + " = :lockUntil WHERE " + name() + " = :name AND " + lockedBy() + " = :lockedBy AND " + lockUntil() + " > :now"; + return "UPDATE " + tableName() + " SET " + lockUntil() + " = :lockUntil WHERE " + name() + " = :name AND " + + lockedBy() + " = :lockedBy AND " + lockUntil() + " > :now"; } public String getUnlockStatement() { diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/AbstractJdbcTemplateLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/AbstractJdbcTemplateLockProviderIntegrationTest.java index 5a59dc18e..ba5a77a2b 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/AbstractJdbcTemplateLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/AbstractJdbcTemplateLockProviderIntegrationTest.java @@ -1,20 +1,21 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; +import static net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration.builder; +import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; + import net.javacrumbs.shedlock.support.StorageBasedLockProvider; import net.javacrumbs.shedlock.test.support.jdbc.AbstractJdbcLockProviderIntegrationTest; import net.javacrumbs.shedlock.test.support.jdbc.DbConfig; @@ -24,9 +25,6 @@ import org.junit.jupiter.api.TestInstance; import org.springframework.jdbc.core.JdbcTemplate; -import static net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration.builder; -import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; - @TestInstance(PER_CLASS) public abstract class AbstractJdbcTemplateLockProviderIntegrationTest { private final DbConfig dbConfig; @@ -35,7 +33,6 @@ public AbstractJdbcTemplateLockProviderIntegrationTest(DbConfig dbConfig) { this.dbConfig = dbConfig; } - @BeforeAll public void startDb() { dbConfig.startDb(); @@ -45,6 +42,7 @@ public void startDb() { public void shutdownDb() { dbConfig.shutdownDb(); } + @Nested class ClientTime extends AbstractJdbcLockProviderIntegrationTest { @Override @@ -55,9 +53,8 @@ protected DbConfig getDbConfig() { @Override protected StorageBasedLockProvider getLockProvider() { return new JdbcTemplateLockProvider(builder() - .withJdbcTemplate(new JdbcTemplate(getDatasource())) - .build() - ); + .withJdbcTemplate(new JdbcTemplate(getDatasource())) + .build()); } @Override @@ -75,12 +72,10 @@ protected DbConfig getDbConfig() { @Override protected StorageBasedLockProvider getLockProvider() { - return new JdbcTemplateLockProvider(JdbcTemplateLockProvider.Configuration - .builder() - .withJdbcTemplate(new JdbcTemplate(getDatasource())) - .usingDbTime() - .build() - ); + return new JdbcTemplateLockProvider(JdbcTemplateLockProvider.Configuration.builder() + .withJdbcTemplate(new JdbcTemplate(getDatasource())) + .usingDbTime() + .build()); } @Override @@ -96,5 +91,3 @@ class StorageAccessor extends AbstractJdbcTemplateStorageAccessorTest { } } } - - diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/AbstractJdbcTemplateStorageAccessorTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/AbstractJdbcTemplateStorageAccessorTest.java index 044d5970e..75490247c 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/AbstractJdbcTemplateStorageAccessorTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/AbstractJdbcTemplateStorageAccessorTest.java @@ -1,20 +1,24 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; +import static java.lang.Thread.sleep; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Timestamp; +import java.time.Duration; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.support.annotation.NonNull; import net.javacrumbs.shedlock.test.support.jdbc.DbConfig; @@ -22,13 +26,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import java.sql.Timestamp; -import java.time.Duration; - -import static java.lang.Thread.sleep; -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static org.assertj.core.api.Assertions.assertThat; - public abstract class AbstractJdbcTemplateStorageAccessorTest { private static final String MY_LOCK = "my-lock"; @@ -58,15 +55,13 @@ void shouldNotUpdateOnInsertIfPreviousDidNotEndWhenUsingDbTime() { private void shouldNotUpdateOnInsertIfPreviousDidNotEnd(boolean usingDbTime) { JdbcTemplateStorageAccessor accessor = getAccessor(usingDbTime); - assertThat( - accessor.insertRecord(lockConfig(MY_LOCK, Duration.ofSeconds(10))) - ).isEqualTo(true); + assertThat(accessor.insertRecord(lockConfig(MY_LOCK, Duration.ofSeconds(10)))) + .isEqualTo(true); Timestamp originalLockValidity = testUtils.getLockedUntil(MY_LOCK); - assertThat( - accessor.insertRecord(lockConfig(MY_LOCK, Duration.ofSeconds(10))) - ).isEqualTo(false); + assertThat(accessor.insertRecord(lockConfig(MY_LOCK, Duration.ofSeconds(10)))) + .isEqualTo(false); assertThat(testUtils.getLockedUntil(MY_LOCK)).isEqualTo(originalLockValidity); } @@ -92,13 +87,14 @@ private void shouldNotUpdateOtherLockConfigurations(boolean usingDbTime) throws Timestamp otherLockLockedUntil = testUtils.getLockedUntil(OTHER_LOCK); // wait for a while so there will be a difference in the timestamp - // when system time is used seems there is no milliseconds in the timestamp so to make a difference we have to wait for at least a second + // when system time is used seems there is no milliseconds in the timestamp so + // to make a + // difference we have to wait for at least a second sleep(1000); - // act - assertThat(accessor.updateRecord(new LockConfiguration(now(), MY_LOCK, lockAtMostFor, Duration.ZERO))).isEqualTo(true); - + assertThat(accessor.updateRecord(new LockConfiguration(now(), MY_LOCK, lockAtMostFor, Duration.ZERO))) + .isEqualTo(true); // assert assertThat(testUtils.getLockedUntil(MY_LOCK)).isAfter(myLockLockedUntil); @@ -113,9 +109,8 @@ private LockConfiguration lockConfig(String myLock, Duration lockAtMostFor) { @NonNull protected JdbcTemplateStorageAccessor getAccessor(boolean usingDbTime) { - JdbcTemplateLockProvider.Configuration.Builder builder = JdbcTemplateLockProvider - .Configuration.builder() - .withJdbcTemplate(testUtils.getJdbcTemplate()); + JdbcTemplateLockProvider.Configuration.Builder builder = + JdbcTemplateLockProvider.Configuration.builder().withJdbcTemplate(testUtils.getJdbcTemplate()); if (usingDbTime) { builder.usingDbTime(); } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/Db2JdbcTemplateLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/Db2JdbcTemplateLockProviderIntegrationTest.java index 155f527a6..c472578b3 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/Db2JdbcTemplateLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/Db2JdbcTemplateLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/H2JdbcTemplateLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/H2JdbcTemplateLockProviderIntegrationTest.java index 48d10cce4..a66742b42 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/H2JdbcTemplateLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/H2JdbcTemplateLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/HsqlJdbcTemplateLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/HsqlJdbcTemplateLockProviderIntegrationTest.java index 75d2f408a..12ffb4b19 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/HsqlJdbcTemplateLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/HsqlJdbcTemplateLockProviderIntegrationTest.java @@ -1,35 +1,32 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; -import net.javacrumbs.shedlock.core.LockConfiguration; -import net.javacrumbs.shedlock.core.SimpleLock; -import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.ColumnNames; -import net.javacrumbs.shedlock.test.support.jdbc.HsqlConfig; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.core.JdbcTemplate; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration.builder; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.time.Duration; import java.util.Optional; - -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration.builder; +import net.javacrumbs.shedlock.core.LockConfiguration; +import net.javacrumbs.shedlock.core.SimpleLock; +import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.ColumnNames; +import net.javacrumbs.shedlock.test.support.jdbc.HsqlConfig; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; public class HsqlJdbcTemplateLockProviderIntegrationTest extends AbstractJdbcTemplateLockProviderIntegrationTest { private static final HsqlConfig dbConfig = new HsqlConfig(); @@ -40,21 +37,21 @@ public HsqlJdbcTemplateLockProviderIntegrationTest() { @Test public void shouldBeAbleToSetCustomColumnNames() throws SQLException { - try ( - Connection conn = dbConfig.getDataSource().getConnection(); - Statement statement = conn.createStatement() - ) { - statement.execute("CREATE TABLE shdlck(n VARCHAR(64), lck_untl TIMESTAMP(3), lckd_at TIMESTAMP(3), lckd_by VARCHAR(255), PRIMARY KEY (n))"); + try (Connection conn = dbConfig.getDataSource().getConnection(); + Statement statement = conn.createStatement()) { + statement.execute( + "CREATE TABLE shdlck(n VARCHAR(64), lck_untl TIMESTAMP(3), lckd_at TIMESTAMP(3), lckd_by VARCHAR(255), PRIMARY KEY (n))"); } JdbcTemplateLockProvider provider = new JdbcTemplateLockProvider(builder() - .withTableName("shdlck") - .withColumnNames(new ColumnNames("n", "lck_untl", "lckd_at", "lckd_by")) - .withJdbcTemplate(new JdbcTemplate(dbConfig.getDataSource())) - .withLockedByValue("my-value") - .build()); - - Optional lock = provider.lock(new LockConfiguration(now(), "test", Duration.ofSeconds(10), Duration.ZERO)); + .withTableName("shdlck") + .withColumnNames(new ColumnNames("n", "lck_untl", "lckd_at", "lckd_by")) + .withJdbcTemplate(new JdbcTemplate(dbConfig.getDataSource())) + .withLockedByValue("my-value") + .build()); + + Optional lock = + provider.lock(new LockConfiguration(now(), "test", Duration.ofSeconds(10), Duration.ZERO)); lock.get().unlock(); } } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateLockProviderTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateLockProviderTest.java index 0e4fecc46..baefda825 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateLockProviderTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateLockProviderTest.java @@ -1,50 +1,43 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.core.JdbcTemplate; - -import java.util.TimeZone; - import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import java.util.TimeZone; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; class JdbcTemplateLockProviderTest { @Test void shouldNotEnableBothTimezoneAndServerTime() { - assertThatThrownBy( - () -> JdbcTemplateLockProvider.Configuration.builder() - .withTimeZone(TimeZone.getTimeZone("Europe/Prague")) - .withJdbcTemplate(mock(JdbcTemplate.class)) - .usingDbTime() - .build() - ).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> JdbcTemplateLockProvider.Configuration.builder() + .withTimeZone(TimeZone.getTimeZone("Europe/Prague")) + .withJdbcTemplate(mock(JdbcTemplate.class)) + .usingDbTime() + .build()) + .isInstanceOf(IllegalArgumentException.class); } @Test void shouldTableAndColumNamesUpperCase() { - final var config = JdbcTemplateLockProvider - .Configuration - .builder() - .withJdbcTemplate(mock(JdbcTemplate.class)) - .withDbUpperCase(true) - .build(); + final var config = JdbcTemplateLockProvider.Configuration.builder() + .withJdbcTemplate(mock(JdbcTemplate.class)) + .withDbUpperCase(true) + .build(); assertThat(config.getTableName()).isUpperCase(); assertThat(config.getColumnNames().getName()).isUpperCase(); @@ -55,11 +48,9 @@ void shouldTableAndColumNamesUpperCase() { @Test void shouldTableAndColumNamesLowerCaseByDefault() { - final var config = JdbcTemplateLockProvider - .Configuration - .builder() - .withJdbcTemplate(mock(JdbcTemplate.class)) - .build(); + final var config = JdbcTemplateLockProvider.Configuration.builder() + .withJdbcTemplate(mock(JdbcTemplate.class)) + .build(); assertThat(config.getTableName()).isLowerCase(); assertThat(config.getColumnNames().getName()).isLowerCase(); diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateStorageAccessorTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateStorageAccessorTest.java index a489d2ea9..9b96b4534 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateStorageAccessorTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/JdbcTemplateStorageAccessorTest.java @@ -1,41 +1,34 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.core.JdbcTemplate; - -import javax.sql.DataSource; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; +import javax.sql.DataSource; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; + class JdbcTemplateStorageAccessorTest { @Test void shouldDoLazyInit() { DataSource dataSource = mock(DataSource.class); - new JdbcTemplateStorageAccessor( - JdbcTemplateLockProvider.Configuration - .builder() + new JdbcTemplateStorageAccessor(JdbcTemplateLockProvider.Configuration.builder() .withJdbcTemplate(new JdbcTemplate(dataSource)) - .build() - ); + .build()); verifyNoInteractions(dataSource); } - } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MariaDbJdbcTemplateLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MariaDbJdbcTemplateLockProviderIntegrationTest.java index 7a075dff2..6cde33edc 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MariaDbJdbcTemplateLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MariaDbJdbcTemplateLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MsSqlServerJdbcTemplateLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MsSqlServerJdbcTemplateLockProviderIntegrationTest.java index ac16d7e97..f333af2f7 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MsSqlServerJdbcTemplateLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MsSqlServerJdbcTemplateLockProviderIntegrationTest.java @@ -1,23 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; import net.javacrumbs.shedlock.test.support.jdbc.MsSqlServerConfig; -public class MsSqlServerJdbcTemplateLockProviderIntegrationTest extends AbstractJdbcTemplateLockProviderIntegrationTest { +public class MsSqlServerJdbcTemplateLockProviderIntegrationTest + extends AbstractJdbcTemplateLockProviderIntegrationTest { private static final MsSqlServerConfig dbConfig = new MsSqlServerConfig(); public MsSqlServerJdbcTemplateLockProviderIntegrationTest() { diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MultiTenancyLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MultiTenancyLockProviderIntegrationTest.java index 8d8a2fca9..30eb47ac2 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MultiTenancyLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MultiTenancyLockProviderIntegrationTest.java @@ -1,20 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration.builder; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Duration; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; @@ -28,19 +35,10 @@ import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; -import java.time.Duration; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; - -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration.builder; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - public class MultiTenancyLockProviderIntegrationTest { public static final String LOCK_NAME = "lock_name"; - public static final LockConfiguration LOCK_CONFIGURATION = new LockConfiguration(now(), LOCK_NAME, Duration.ofSeconds(60), Duration.ZERO); + public static final LockConfiguration LOCK_CONFIGURATION = + new LockConfiguration(now(), LOCK_NAME, Duration.ofSeconds(60), Duration.ZERO); private static final JdbcTestUtils h2TestUtils; private static final JdbcTestUtils hsqlTestUtils; @@ -61,7 +59,8 @@ void shouldUseDifferDatabaseForEachTennant() { Optional lock1 = lockProvider.lock(LOCK_CONFIGURATION); assertThat(lock1).isNotEmpty(); assertThat(h2TestUtils.getLockInfo(LOCK_NAME).getLockUntil()).isAfter(ClockProvider.now()); - assertThatThrownBy(() -> hsqlTestUtils.getLockedUntil(LOCK_NAME)).isInstanceOf(EmptyResultDataAccessException.class); + assertThatThrownBy(() -> hsqlTestUtils.getLockedUntil(LOCK_NAME)) + .isInstanceOf(EmptyResultDataAccessException.class); lock1.get().unlock(); @@ -81,16 +80,18 @@ private LockProvider getLockProvider() { return new SampleLockProvider(h2TestUtils.getJdbcTemplate(), hsqlTestUtils.getJdbcTemplate()); } - private static abstract class MultiTenancyLockProvider implements LockProvider { + private abstract static class MultiTenancyLockProvider implements LockProvider { private final ConcurrentHashMap providers = new ConcurrentHashMap<>(); @Override public @NonNull Optional lock(@NonNull LockConfiguration lockConfiguration) { String tenantName = getTenantName(lockConfiguration); - return providers.computeIfAbsent(tenantName, this::createLockProvider).lock(lockConfiguration); + return providers + .computeIfAbsent(tenantName, this::createLockProvider) + .lock(lockConfiguration); } - protected abstract LockProvider createLockProvider(String tenantName) ; + protected abstract LockProvider createLockProvider(String tenantName); protected abstract String getTenantName(LockConfiguration lockConfiguration); } @@ -107,19 +108,14 @@ private SampleLockProvider(JdbcTemplate jdbcTemplate1, JdbcTemplate jdbcTemplate this.jdbcTemplate2 = jdbcTemplate2; } - @Override protected LockProvider createLockProvider(String tenantName) { if (TENANT_1.equals(tenantName)) { - return new JdbcTemplateLockProvider(builder() - .withJdbcTemplate(jdbcTemplate1) - .build() - ); + return new JdbcTemplateLockProvider( + builder().withJdbcTemplate(jdbcTemplate1).build()); } else { - return new JdbcTemplateLockProvider(builder() - .withJdbcTemplate(jdbcTemplate2) - .build() - ); + return new JdbcTemplateLockProvider( + builder().withJdbcTemplate(jdbcTemplate2).build()); } } @@ -135,5 +131,3 @@ protected String getTenantName(LockConfiguration lockConfiguration) { } } } - - diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MySqlJdbcTemplateLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MySqlJdbcTemplateLockProviderIntegrationTest.java index 54ae32fb3..edd12c8fc 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MySqlJdbcTemplateLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/MySqlJdbcTemplateLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; @@ -23,5 +21,4 @@ public class MySqlJdbcTemplateLockProviderIntegrationTest extends AbstractJdbcTe protected MySqlJdbcTemplateLockProviderIntegrationTest() { super(dbConfig); } - } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/OracleJdbcTemplateLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/OracleJdbcTemplateLockProviderIntegrationTest.java index 0322e9f84..b35735977 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/OracleJdbcTemplateLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/OracleJdbcTemplateLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresJdbcTemplateLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresJdbcTemplateLockProviderIntegrationTest.java index d4c59b11c..8a96c0aa9 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresJdbcTemplateLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresJdbcTemplateLockProviderIntegrationTest.java @@ -1,40 +1,37 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; -import net.javacrumbs.shedlock.core.ClockProvider; -import net.javacrumbs.shedlock.core.LockConfiguration; -import net.javacrumbs.shedlock.test.support.jdbc.PostgresConfig; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.core.JdbcTemplate; +import static java.lang.Thread.sleep; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration.builder; +import static org.assertj.core.api.Assertions.assertThat; -import javax.sql.DataSource; import java.sql.Connection; import java.sql.Timestamp; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.TimeZone; - -import static java.lang.Thread.sleep; -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration.builder; -import static org.assertj.core.api.Assertions.assertThat; +import javax.sql.DataSource; +import net.javacrumbs.shedlock.core.ClockProvider; +import net.javacrumbs.shedlock.core.LockConfiguration; +import net.javacrumbs.shedlock.test.support.jdbc.PostgresConfig; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; public class PostgresJdbcTemplateLockProviderIntegrationTest extends AbstractJdbcTemplateLockProviderIntegrationTest { private static final PostgresConfig dbConfig = new PostgresConfig(); @@ -59,24 +56,23 @@ void shouldHonorTimezone() { TimeZone originalTimezone = TimeZone.getDefault(); - DataSource datasource = dbConfig.getDataSource(); TimeZone.setDefault(timezone); try { JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); - jdbcTemplate.execute("CREATE TABLE shedlock_tz(name VARCHAR(64), lock_until TIMESTAMP WITH TIME ZONE, locked_at TIMESTAMP WITH TIME ZONE, locked_by VARCHAR(255), PRIMARY KEY (name))"); + jdbcTemplate.execute( + "CREATE TABLE shedlock_tz(name VARCHAR(64), lock_until TIMESTAMP WITH TIME ZONE, locked_at TIMESTAMP WITH TIME ZONE, locked_by VARCHAR(255), PRIMARY KEY (name))"); JdbcTemplateLockProvider provider = new JdbcTemplateLockProvider(builder() - .withJdbcTemplate(new JdbcTemplate(datasource)) - .withTableName("shedlock_tz") - .withTimeZone(timezone) - .withIsolationLevel(Connection.TRANSACTION_SERIALIZABLE) - .build()); + .withJdbcTemplate(new JdbcTemplate(datasource)) + .withTableName("shedlock_tz") + .withTimeZone(timezone) + .withIsolationLevel(Connection.TRANSACTION_SERIALIZABLE) + .build()); - - provider.lock(new LockConfiguration(now, "timezone_test",Duration.ofSeconds(10), Duration.ZERO)); + provider.lock(new LockConfiguration(now, "timezone_test", Duration.ofSeconds(10), Duration.ZERO)); new JdbcTemplate(datasource).query("SELECT * FROM shedlock_tz where name='timezone_test'", rs -> { Timestamp timestamp = rs.getTimestamp("lock_until"); assertThat(timestamp.getTimezoneOffset()).isEqualTo(7 * 60); @@ -110,23 +106,21 @@ void shouldUpdateOnInsertAfterValidityOfPreviousEndedWhenUsingDbTime() throws In private void shouldUpdateOnInsertAfterValidityOfPreviousEnded(boolean usingDbTime) throws InterruptedException { JdbcTemplateStorageAccessor accessor = getAccessor(usingDbTime); - accessor.insertRecord(new LockConfiguration(now(), OTHER_LOCK, Duration.ofSeconds(5), Duration.ZERO)); Timestamp otherLockValidity = getTestUtils().getLockedUntil(OTHER_LOCK); - assertThat( - accessor.insertRecord(new LockConfiguration(now(), MY_LOCK, Duration.ofMillis(10), Duration.ZERO)) - ).isEqualTo(true); + assertThat(accessor.insertRecord( + new LockConfiguration(now(), MY_LOCK, Duration.ofMillis(10), Duration.ZERO))) + .isEqualTo(true); sleep(10); - assertThat( - accessor.insertRecord(new LockConfiguration(now(), MY_LOCK, Duration.ofMillis(10), Duration.ZERO)) - ).isEqualTo(true); + assertThat(accessor.insertRecord( + new LockConfiguration(now(), MY_LOCK, Duration.ofMillis(10), Duration.ZERO))) + .isEqualTo(true); // check that the other lock has not been affected by "my-lock" update assertThat(getTestUtils().getLockedUntil(OTHER_LOCK)).isEqualTo(otherLockValidity); } } - } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresSerializableJdbcTemplateLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresSerializableJdbcTemplateLockProviderIntegrationTest.java index ab854464c..cc6e09de2 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresSerializableJdbcTemplateLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/PostgresSerializableJdbcTemplateLockProviderIntegrationTest.java @@ -1,20 +1,21 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; +import static net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration.builder; + +import java.sql.Connection; import net.javacrumbs.shedlock.support.StorageBasedLockProvider; import net.javacrumbs.shedlock.test.support.jdbc.AbstractJdbcLockProviderIntegrationTest; import net.javacrumbs.shedlock.test.support.jdbc.DbConfig; @@ -23,11 +24,8 @@ import org.junit.jupiter.api.BeforeAll; import org.springframework.jdbc.core.JdbcTemplate; -import java.sql.Connection; - -import static net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider.Configuration.builder; - -public class PostgresSerializableJdbcTemplateLockProviderIntegrationTest extends AbstractJdbcLockProviderIntegrationTest { +public class PostgresSerializableJdbcTemplateLockProviderIntegrationTest + extends AbstractJdbcLockProviderIntegrationTest { private static final PostgresConfig dbConfig = new PostgresConfig(); @BeforeAll @@ -53,9 +51,7 @@ protected boolean useDbTime() { @Override protected StorageBasedLockProvider getLockProvider() { - return new JdbcTemplateLockProvider(builder() - .withJdbcTemplate(new JdbcTemplate(getDatasource())) - .build() - ); + return new JdbcTemplateLockProvider( + builder().withJdbcTemplate(new JdbcTemplate(getDatasource())).build()); } } diff --git a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/ServerTimeTest.java b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/ServerTimeTest.java index 96fd23509..3b094d8b0 100644 --- a/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/ServerTimeTest.java +++ b/providers/jdbc/shedlock-provider-jdbc-template/src/test/java/net/javacrumbs/shedlock/provider/jdbctemplate/ServerTimeTest.java @@ -1,34 +1,31 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbctemplate; -import net.javacrumbs.shedlock.core.LockConfiguration; -import net.javacrumbs.shedlock.core.SimpleLock; -import net.javacrumbs.shedlock.support.StorageBasedLockProvider; -import net.javacrumbs.shedlock.test.support.jdbc.JdbcTestUtils; -import org.junit.jupiter.api.Test; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Optional; - -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static org.assertj.core.api.Assertions.assertThat; +import net.javacrumbs.shedlock.core.LockConfiguration; +import net.javacrumbs.shedlock.core.SimpleLock; +import net.javacrumbs.shedlock.support.StorageBasedLockProvider; +import net.javacrumbs.shedlock.test.support.jdbc.JdbcTestUtils; +import org.junit.jupiter.api.Test; public interface ServerTimeTest { @@ -41,16 +38,20 @@ public interface ServerTimeTest { @Test default void lockUntilShouldBeInUtc() { Instant time = Instant.now(); - Optional lock = getLockProvider().lock(new LockConfiguration(now(), LOCK_NAME, Duration.ofSeconds(60), Duration.ZERO)); - assertThat(getTestUtils().getLockedUntil(LOCK_NAME).toLocalDateTime()).isBetween(atUtc(time.plusSeconds(50)), atUtc(time.plusSeconds(70))); + Optional lock = + getLockProvider().lock(new LockConfiguration(now(), LOCK_NAME, Duration.ofSeconds(60), Duration.ZERO)); + assertThat(getTestUtils().getLockedUntil(LOCK_NAME).toLocalDateTime()) + .isBetween(atUtc(time.plusSeconds(50)), atUtc(time.plusSeconds(70))); time = Instant.now(); lock.get().unlock(); - assertThat(getTestUtils().getLockedUntil(LOCK_NAME).toLocalDateTime()).isBetween(atUtc(time.minusSeconds(10)), atUtc(time.plusSeconds(10))); + assertThat(getTestUtils().getLockedUntil(LOCK_NAME).toLocalDateTime()) + .isBetween(atUtc(time.minusSeconds(10)), atUtc(time.plusSeconds(10))); time = Instant.now(); getLockProvider().lock(new LockConfiguration(now(), LOCK_NAME, Duration.ofSeconds(120), Duration.ZERO)); - assertThat(getTestUtils().getLockedUntil(LOCK_NAME).toLocalDateTime()).isBetween(atUtc(time.plusSeconds(110)), atUtc(time.plusSeconds(130))); + assertThat(getTestUtils().getLockedUntil(LOCK_NAME).toLocalDateTime()) + .isBetween(atUtc(time.plusSeconds(110)), atUtc(time.plusSeconds(130))); } static LocalDateTime atUtc(Instant before) { diff --git a/providers/jdbc/shedlock-provider-jdbc/src/main/java/net/javacrumbs/shedlock/provider/jdbc/JdbcLockProvider.java b/providers/jdbc/shedlock-provider-jdbc/src/main/java/net/javacrumbs/shedlock/provider/jdbc/JdbcLockProvider.java index 3f52ed20a..769129552 100644 --- a/providers/jdbc/shedlock-provider-jdbc/src/main/java/net/javacrumbs/shedlock/provider/jdbc/JdbcLockProvider.java +++ b/providers/jdbc/shedlock-provider-jdbc/src/main/java/net/javacrumbs/shedlock/provider/jdbc/JdbcLockProvider.java @@ -1,45 +1,37 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbc; +import javax.sql.DataSource; import net.javacrumbs.shedlock.support.StorageBasedLockProvider; import net.javacrumbs.shedlock.support.annotation.NonNull; -import javax.sql.DataSource; - /** - * Lock provided by plain JDBC. It uses a table that contains lock_name and locked_until. + * Lock provided by plain JDBC. It uses a table that contains lock_name and + * locked_until. + * *

    - *
  1. - * Attempts to insert a new lock record. Since lock name is a primary key, it fails if the record already exists. As an optimization, - * we keep in-memory track of created lock records. - *
  2. - *
  3. - * If the insert succeeds (1 inserted row) we have the lock. - *
  4. - *
  5. - * If the insert failed due to duplicate key or we have skipped the insertion, we will try to update lock record using - * UPDATE tableName SET lock_until = :lockUntil WHERE name = :lockName AND lock_until <= :now - *
  6. - *
  7. - * If the update succeeded (1 updated row), we have the lock. If the update failed (0 updated rows) somebody else holds the lock - *
  8. - *
  9. - * When unlocking, lock_until is set to now. - *
  10. + *
  11. Attempts to insert a new lock record. Since lock name is a primary key, + * it fails if the record already exists. As an optimization, we keep in-memory + * track of created lock records. + *
  12. If the insert succeeds (1 inserted row) we have the lock. + *
  13. If the insert failed due to duplicate key or we have skipped the + * insertion, we will try to update lock record using UPDATE tableName SET + * lock_until = :lockUntil WHERE name = :lockName AND lock_until <= :now + *
  14. If the update succeeded (1 updated row), we have the lock. If the update + * failed (0 updated rows) somebody else holds the lock + *
  15. When unlocking, lock_until is set to now. *
*/ public class JdbcLockProvider extends StorageBasedLockProvider { diff --git a/providers/jdbc/shedlock-provider-jdbc/src/main/java/net/javacrumbs/shedlock/provider/jdbc/JdbcStorageAccessor.java b/providers/jdbc/shedlock-provider-jdbc/src/main/java/net/javacrumbs/shedlock/provider/jdbc/JdbcStorageAccessor.java index aef34ed02..3cfa76a68 100644 --- a/providers/jdbc/shedlock-provider-jdbc/src/main/java/net/javacrumbs/shedlock/provider/jdbc/JdbcStorageAccessor.java +++ b/providers/jdbc/shedlock-provider-jdbc/src/main/java/net/javacrumbs/shedlock/provider/jdbc/JdbcStorageAccessor.java @@ -1,30 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbc; -import net.javacrumbs.shedlock.provider.jdbc.internal.AbstractJdbcStorageAccessor; -import net.javacrumbs.shedlock.support.annotation.NonNull; +import static java.util.Objects.requireNonNull; -import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.function.BiFunction; - -import static java.util.Objects.requireNonNull; +import javax.sql.DataSource; +import net.javacrumbs.shedlock.provider.jdbc.internal.AbstractJdbcStorageAccessor; +import net.javacrumbs.shedlock.support.annotation.NonNull; class JdbcStorageAccessor extends AbstractJdbcStorageAccessor { private final DataSource dataSource; @@ -36,10 +33,7 @@ class JdbcStorageAccessor extends AbstractJdbcStorageAccessor { @Override protected T executeCommand( - String sql, - SqlFunction body, - BiFunction exceptionHandler - ) { + String sql, SqlFunction body, BiFunction exceptionHandler) { try (Connection connection = dataSource.getConnection()) { boolean originalAutocommit = connection.getAutoCommit(); if (!originalAutocommit) { diff --git a/providers/jdbc/shedlock-provider-jdbc/src/test/java/net/javacrumbs/shedlock/provider/jdbc/HsqlJdbcLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc/src/test/java/net/javacrumbs/shedlock/provider/jdbc/HsqlJdbcLockProviderIntegrationTest.java index 6c18cbcd2..a7695efc1 100644 --- a/providers/jdbc/shedlock-provider-jdbc/src/test/java/net/javacrumbs/shedlock/provider/jdbc/HsqlJdbcLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc/src/test/java/net/javacrumbs/shedlock/provider/jdbc/HsqlJdbcLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbc; diff --git a/providers/jdbc/shedlock-provider-jdbc/src/test/java/net/javacrumbs/shedlock/provider/jdbc/MySqlJdbcLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc/src/test/java/net/javacrumbs/shedlock/provider/jdbc/MySqlJdbcLockProviderIntegrationTest.java index c8f58a5be..aece61ba0 100644 --- a/providers/jdbc/shedlock-provider-jdbc/src/test/java/net/javacrumbs/shedlock/provider/jdbc/MySqlJdbcLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc/src/test/java/net/javacrumbs/shedlock/provider/jdbc/MySqlJdbcLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbc; diff --git a/providers/jdbc/shedlock-provider-jdbc/src/test/java/net/javacrumbs/shedlock/provider/jdbc/PostgresJdbcLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jdbc/src/test/java/net/javacrumbs/shedlock/provider/jdbc/PostgresJdbcLockProviderIntegrationTest.java index 6bf9c94d4..e2e08a993 100644 --- a/providers/jdbc/shedlock-provider-jdbc/src/test/java/net/javacrumbs/shedlock/provider/jdbc/PostgresJdbcLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jdbc/src/test/java/net/javacrumbs/shedlock/provider/jdbc/PostgresJdbcLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jdbc; diff --git a/providers/jdbc/shedlock-provider-jooq/src/main/java/net/javacrumbs/shedlock/provider/jooq/JooqLockProvider.java b/providers/jdbc/shedlock-provider-jooq/src/main/java/net/javacrumbs/shedlock/provider/jooq/JooqLockProvider.java index 3d6811b00..85e7f27b0 100644 --- a/providers/jdbc/shedlock-provider-jooq/src/main/java/net/javacrumbs/shedlock/provider/jooq/JooqLockProvider.java +++ b/providers/jdbc/shedlock-provider-jooq/src/main/java/net/javacrumbs/shedlock/provider/jooq/JooqLockProvider.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jooq; @@ -19,7 +17,6 @@ import net.javacrumbs.shedlock.support.annotation.NonNull; import org.jooq.DSLContext; - public class JooqLockProvider extends StorageBasedLockProvider { public JooqLockProvider(@NonNull DSLContext dslContext) { super(new JooqStorageAccessor(dslContext)); diff --git a/providers/jdbc/shedlock-provider-jooq/src/main/java/net/javacrumbs/shedlock/provider/jooq/JooqStorageAccessor.java b/providers/jdbc/shedlock-provider-jooq/src/main/java/net/javacrumbs/shedlock/provider/jooq/JooqStorageAccessor.java index 4d7649d5c..2adc752b6 100644 --- a/providers/jdbc/shedlock-provider-jooq/src/main/java/net/javacrumbs/shedlock/provider/jooq/JooqStorageAccessor.java +++ b/providers/jdbc/shedlock-provider-jooq/src/main/java/net/javacrumbs/shedlock/provider/jooq/JooqStorageAccessor.java @@ -1,5 +1,15 @@ package net.javacrumbs.shedlock.provider.jooq; +import static net.javacrumbs.shedlock.provider.jooq.Shedlock.SHEDLOCK; +import static org.jooq.impl.DSL.currentLocalDateTime; +import static org.jooq.impl.DSL.inline; +import static org.jooq.impl.DSL.localDateTimeAdd; +import static org.jooq.impl.DSL.when; + +import java.io.Serializable; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.Map; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.support.AbstractStorageAccessor; import net.javacrumbs.shedlock.support.annotation.NonNull; @@ -9,17 +19,6 @@ import org.jooq.TableField; import org.jooq.types.DayToSecond; -import java.io.Serializable; -import java.time.Duration; -import java.time.LocalDateTime; -import java.util.Map; - -import static net.javacrumbs.shedlock.provider.jooq.Shedlock.SHEDLOCK; -import static org.jooq.impl.DSL.currentLocalDateTime; -import static org.jooq.impl.DSL.inline; -import static org.jooq.impl.DSL.localDateTimeAdd; -import static org.jooq.impl.DSL.when; - class JooqStorageAccessor extends AbstractStorageAccessor { private final DSLContext dslContext; private final Shedlock t = SHEDLOCK; @@ -30,43 +29,60 @@ class JooqStorageAccessor extends AbstractStorageAccessor { @Override public boolean insertRecord(@NonNull LockConfiguration lockConfiguration) { - return dslContext.transactionResult(tx -> tx.dsl().insertInto(t) - .set(data(lockConfiguration)) - .onConflictDoNothing() - .execute() > 0); + return dslContext.transactionResult(tx -> tx.dsl() + .insertInto(t) + .set(data(lockConfiguration)) + .onConflictDoNothing() + .execute() + > 0); } @Override public boolean updateRecord(@NonNull LockConfiguration lockConfiguration) { - return dslContext.transactionResult(tx -> tx.dsl().update(t) - .set(data(lockConfiguration)) - .where(t.NAME.eq(lockConfiguration.getName()).and(t.LOCK_UNTIL.le(now()))) - .execute() > 0); + return dslContext.transactionResult(tx -> tx.dsl() + .update(t) + .set(data(lockConfiguration)) + .where(t.NAME.eq(lockConfiguration.getName()).and(t.LOCK_UNTIL.le(now()))) + .execute() + > 0); } @Override public void unlock(LockConfiguration lockConfiguration) { - Field lockAtLeastFor = t.LOCKED_AT.add(DayToSecond.valueOf(lockConfiguration.getLockAtLeastFor())); - dslContext.transaction(tx -> tx.dsl().update(t).set(t.LOCK_UNTIL, when(lockAtLeastFor.gt(now()), lockAtLeastFor).otherwise(now())) - .where(t.NAME.eq(lockConfiguration.getName()).and(t.LOCKED_BY.eq(getHostname()))) - .execute()); + Field lockAtLeastFor = + t.LOCKED_AT.add(DayToSecond.valueOf(lockConfiguration.getLockAtLeastFor())); + dslContext.transaction(tx -> tx.dsl() + .update(t) + .set( + t.LOCK_UNTIL, + when(lockAtLeastFor.gt(now()), lockAtLeastFor).otherwise(now())) + .where(t.NAME.eq(lockConfiguration.getName()).and(t.LOCKED_BY.eq(getHostname()))) + .execute()); } @Override public boolean extend(@NonNull LockConfiguration lockConfiguration) { - return dslContext.transactionResult(tx -> tx.dsl().update(t).set(t.LOCK_UNTIL, nowPlus(lockConfiguration.getLockAtMostFor())) - .where(t.NAME.eq(lockConfiguration.getName()).and(t.LOCKED_BY.eq(getHostname())).and(t.LOCK_UNTIL.gt(now()))) - .execute() > 0); + return dslContext.transactionResult(tx -> tx.dsl() + .update(t) + .set(t.LOCK_UNTIL, nowPlus(lockConfiguration.getLockAtMostFor())) + .where(t.NAME.eq(lockConfiguration.getName()) + .and(t.LOCKED_BY.eq(getHostname())) + .and(t.LOCK_UNTIL.gt(now()))) + .execute() + > 0); } - - private Map, Serializable> data(LockConfiguration lockConfiguration) { + private Map, Serializable> data( + LockConfiguration lockConfiguration) { return Map.of( - t.NAME, lockConfiguration.getName(), - t.LOCK_UNTIL, nowPlus(lockConfiguration.getLockAtMostFor()), - t.LOCKED_AT, now(), - t.LOCKED_BY, getHostname() - ); + t.NAME, + lockConfiguration.getName(), + t.LOCK_UNTIL, + nowPlus(lockConfiguration.getLockAtMostFor()), + t.LOCKED_AT, + now(), + t.LOCKED_BY, + getHostname()); } private Field now() { diff --git a/providers/jdbc/shedlock-provider-jooq/src/main/java/net/javacrumbs/shedlock/provider/jooq/Shedlock.java b/providers/jdbc/shedlock-provider-jooq/src/main/java/net/javacrumbs/shedlock/provider/jooq/Shedlock.java index 95a2a3187..dc330318d 100644 --- a/providers/jdbc/shedlock-provider-jooq/src/main/java/net/javacrumbs/shedlock/provider/jooq/Shedlock.java +++ b/providers/jdbc/shedlock-provider-jooq/src/main/java/net/javacrumbs/shedlock/provider/jooq/Shedlock.java @@ -1,6 +1,6 @@ package net.javacrumbs.shedlock.provider.jooq; - +import java.time.LocalDateTime; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Name; @@ -14,52 +14,39 @@ import org.jooq.impl.SQLDataType; import org.jooq.impl.TableImpl; -import java.time.LocalDateTime; - - -/** - * This class is generated by jOOQ. - */ -@SuppressWarnings({ "all", "unchecked", "rawtypes" }) +/** This class is generated by jOOQ. */ +@SuppressWarnings({"all", "unchecked", "rawtypes"}) class Shedlock extends TableImpl { private static final long serialVersionUID = 1L; - /** - * The reference instance of public.shedlock - */ + /** The reference instance of public.shedlock */ public static final Shedlock SHEDLOCK = new Shedlock(); - public static final UniqueKey SHEDLOCK_PKEY = Internal.createUniqueKey(Shedlock.SHEDLOCK, DSL.name("shedlock_pkey"), new TableField[] { Shedlock.SHEDLOCK.NAME }, true); + public static final UniqueKey SHEDLOCK_PKEY = Internal.createUniqueKey( + Shedlock.SHEDLOCK, DSL.name("shedlock_pkey"), new TableField[] {Shedlock.SHEDLOCK.NAME}, true); - - /** - * The class holding records for this type - */ + /** The class holding records for this type */ @Override public Class getRecordType() { return Record.class; } - /** - * The column public.shedlock.name. - */ - public final TableField NAME = createField(DSL.name("name"), SQLDataType.VARCHAR(64).nullable(false), this, ""); + /** The column public.shedlock.name. */ + public final TableField NAME = + createField(DSL.name("name"), SQLDataType.VARCHAR(64).nullable(false), this, ""); - /** - * The column public.shedlock.lock_until. - */ - public final TableField LOCK_UNTIL = createField(DSL.name("lock_until"), SQLDataType.LOCALDATETIME(6).nullable(false), this, ""); + /** The column public.shedlock.lock_until. */ + public final TableField LOCK_UNTIL = + createField(DSL.name("lock_until"), SQLDataType.LOCALDATETIME(6).nullable(false), this, ""); - /** - * The column public.shedlock.locked_at. - */ - public final TableField LOCKED_AT = createField(DSL.name("locked_at"), SQLDataType.LOCALDATETIME(6).nullable(false), this, ""); + /** The column public.shedlock.locked_at. */ + public final TableField LOCKED_AT = + createField(DSL.name("locked_at"), SQLDataType.LOCALDATETIME(6).nullable(false), this, ""); - /** - * The column public.shedlock.locked_by. - */ - public final TableField LOCKED_BY = createField(DSL.name("locked_by"), SQLDataType.VARCHAR(255).nullable(false), this, ""); + /** The column public.shedlock.locked_by. */ + public final TableField LOCKED_BY = + createField(DSL.name("locked_by"), SQLDataType.VARCHAR(255).nullable(false), this, ""); private Shedlock(Name alias, Table aliased) { this(alias, aliased, null); @@ -69,23 +56,17 @@ private Shedlock(Name alias, Table aliased, Field[] parameters) { super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table()); } - /** - * Create an aliased public.shedlock table reference - */ + /** Create an aliased public.shedlock table reference */ public Shedlock(String alias) { this(DSL.name(alias), SHEDLOCK); } - /** - * Create an aliased public.shedlock table reference - */ + /** Create an aliased public.shedlock table reference */ public Shedlock(Name alias) { this(alias, SHEDLOCK); } - /** - * Create a public.shedlock table reference - */ + /** Create a public.shedlock table reference */ public Shedlock() { this(DSL.name("shedlock"), null); } @@ -94,7 +75,6 @@ public Shedlock(Table child, ForeignKey key) { super(child, key, SHEDLOCK); } - @Override public Shedlock as(String alias) { return new Shedlock(DSL.name(alias), this); @@ -109,34 +89,27 @@ public Shedlock as(Name alias) { public Shedlock as(Table alias) { return new Shedlock(alias.getQualifiedName(), this); } + @Override public UniqueKey getPrimaryKey() { return SHEDLOCK_PKEY; } - /** - * Rename this table - */ + /** Rename this table */ @Override public Shedlock rename(String name) { return new Shedlock(DSL.name(name), null); } - /** - * Rename this table - */ + /** Rename this table */ @Override public Shedlock rename(Name name) { return new Shedlock(name, null); } - /** - * Rename this table - */ + /** Rename this table */ @Override public Shedlock rename(Table name) { return new Shedlock(name.getQualifiedName(), null); } } - - diff --git a/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/AbstractJooqLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/AbstractJooqLockProviderIntegrationTest.java index 2fb828793..9832f5da1 100644 --- a/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/AbstractJooqLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/AbstractJooqLockProviderIntegrationTest.java @@ -1,20 +1,20 @@ /** * Copyright 2009 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + * + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + *

http://www.apache.org/licenses/LICENSE-2.0 + * + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jooq; +import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; + import net.javacrumbs.shedlock.support.StorageBasedLockProvider; import net.javacrumbs.shedlock.test.support.jdbc.AbstractJdbcLockProviderIntegrationTest; import net.javacrumbs.shedlock.test.support.jdbc.DbConfig; @@ -24,8 +24,6 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.TestInstance; -import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; - @TestInstance(PER_CLASS) public abstract class AbstractJooqLockProviderIntegrationTest extends AbstractJdbcLockProviderIntegrationTest { private final DbConfig dbConfig; @@ -52,7 +50,6 @@ protected boolean useDbTime() { return true; } - @BeforeAll public void startDb() { dbConfig.startDb(); @@ -63,5 +60,3 @@ public void shutdownDb() { dbConfig.shutdownDb(); } } - - diff --git a/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/HsqlJooqLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/HsqlJooqLockProviderIntegrationTest.java index 274b22bf7..ee1337f3a 100644 --- a/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/HsqlJooqLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/HsqlJooqLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jooq; @@ -26,6 +24,11 @@ public class HsqlJooqLockProviderIntegrationTest extends AbstractJooqLockProvide private static final DbConfig dbConfig = new HsqlConfig(); public HsqlJooqLockProviderIntegrationTest() { - super(dbConfig, DSL.using(dbConfig.getDataSource(), SQLDialect.HSQLDB, new Settings().withRenderNameCase(RenderNameCase.UPPER))); + super( + dbConfig, + DSL.using( + dbConfig.getDataSource(), + SQLDialect.HSQLDB, + new Settings().withRenderNameCase(RenderNameCase.UPPER))); } } diff --git a/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/MariaDbJooqLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/MariaDbJooqLockProviderIntegrationTest.java index db7f79930..13f9cc875 100644 --- a/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/MariaDbJooqLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/MariaDbJooqLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jooq; diff --git a/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/MySqlJooqLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/MySqlJooqLockProviderIntegrationTest.java index 8f8e08f50..e9ce09a25 100644 --- a/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/MySqlJooqLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/MySqlJooqLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jooq; diff --git a/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/PostgresJooqLockProviderIntegrationTest.java b/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/PostgresJooqLockProviderIntegrationTest.java index 7770781c1..f010e6d6b 100644 --- a/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/PostgresJooqLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-provider-jooq/src/test/java/net/javacrumbs/shedlock/provider/jooq/PostgresJooqLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.jooq; diff --git a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/AbstractContainerBasedDbConfig.java b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/AbstractContainerBasedDbConfig.java index c60f5291c..1e878621b 100644 --- a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/AbstractContainerBasedDbConfig.java +++ b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/AbstractContainerBasedDbConfig.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support.jdbc; @@ -24,8 +22,7 @@ abstract class AbstractContainerBasedDbConfig protected final T container; public AbstractContainerBasedDbConfig(T container) { - this.container = container - .withLogConsumer(outputFrame -> logger.debug(outputFrame.getUtf8String())); + this.container = container.withLogConsumer(outputFrame -> logger.debug(outputFrame.getUtf8String())); } @Override diff --git a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/AbstractDbConfig.java b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/AbstractDbConfig.java index 2fd549f0e..49fb44b31 100644 --- a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/AbstractDbConfig.java +++ b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/AbstractDbConfig.java @@ -1,22 +1,19 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support.jdbc; import com.zaxxer.hikari.HikariDataSource; - import javax.sql.DataSource; abstract class AbstractDbConfig implements DbConfig { @@ -46,9 +43,7 @@ public final void startDb() { dataSource = newDataSource; } - protected void doStartDb() { - - } + protected void doStartDb() {} @Override public final void shutdownDb() { @@ -56,9 +51,7 @@ public final void shutdownDb() { doShutdownDb(); } - protected void doShutdownDb() { - - } + protected void doShutdownDb() {} public void setTransactionIsolation(int transactionIsolation) { this.transactionIsolation = transactionIsolation; diff --git a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/AbstractJdbcLockProviderIntegrationTest.java b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/AbstractJdbcLockProviderIntegrationTest.java index f6b3ce579..d2dcfcc7f 100644 --- a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/AbstractJdbcLockProviderIntegrationTest.java +++ b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/AbstractJdbcLockProviderIntegrationTest.java @@ -1,20 +1,26 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support.jdbc; +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Timestamp; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Optional; +import java.util.concurrent.ExecutionException; +import javax.sql.DataSource; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.SimpleLock; @@ -24,15 +30,6 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import javax.sql.DataSource; -import java.sql.Timestamp; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.Optional; -import java.util.concurrent.ExecutionException; - -import static org.assertj.core.api.Assertions.assertThat; - public abstract class AbstractJdbcLockProviderIntegrationTest extends AbstractStorageBasedLockProviderIntegrationTest { protected JdbcTestUtils testUtils; @@ -53,22 +50,33 @@ public void cleanup() { @Override protected void assertUnlocked(String lockName) { JdbcTestUtils.LockInfo lockInfo = getLockInfo(lockName); - Instant now = useDbTime() ? lockInfo.getDbTime(): ClockProvider.now(); - assertThat(lockInfo.getLockUntil()).describedAs("is unlocked").isBeforeOrEqualTo(now.truncatedTo(ChronoUnit.MILLIS).plusMillis(1)); + Instant now = useDbTime() ? lockInfo.getDbTime() : ClockProvider.now(); + assertThat(lockInfo.getLockUntil()) + .describedAs("is unlocked") + .isBeforeOrEqualTo(now.truncatedTo(ChronoUnit.MILLIS).plusMillis(1)); } @Override protected void assertLocked(String lockName) { JdbcTestUtils.LockInfo lockInfo = getLockInfo(lockName); - Instant now = useDbTime() ? lockInfo.getDbTime(): ClockProvider.now(); + Instant now = useDbTime() ? lockInfo.getDbTime() : ClockProvider.now(); - assertThat(lockInfo.getLockUntil()).describedAs(getClass().getName() + " is locked").isAfter(now); + assertThat(lockInfo.getLockUntil()) + .describedAs(getClass().getName() + " is locked") + .isAfter(now); } @Test public void shouldCreateLockIfRecordAlreadyExists() { Timestamp previousLockTime = Timestamp.from(Instant.now().minus(1, ChronoUnit.DAYS)); - testUtils.getJdbcTemplate().update("INSERT INTO shedlock(name, lock_until, locked_at, locked_by) VALUES(?, ?, ?, ?)", LOCK_NAME1, previousLockTime, previousLockTime, "me"); + testUtils + .getJdbcTemplate() + .update( + "INSERT INTO shedlock(name, lock_until, locked_at, locked_by) VALUES(?, ?, ?, ?)", + LOCK_NAME1, + previousLockTime, + previousLockTime, + "me"); assertUnlocked(LOCK_NAME1); shouldCreateLock(); } @@ -81,7 +89,8 @@ public void fuzzTestShouldWorkWithTransaction() throws ExecutionException, Inter @Test @Disabled public void shouldNotFailIfKeyNameTooLong() { - LockConfiguration configuration = lockConfig("lock name that is too long Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); + LockConfiguration configuration = lockConfig( + "lock name that is too long Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); Optional lock = getLockProvider().lock(configuration); assertThat(lock).isEmpty(); } diff --git a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/Db2ServerConfig.java b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/Db2ServerConfig.java index e093a0220..95a09bcd2 100644 --- a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/Db2ServerConfig.java +++ b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/Db2ServerConfig.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support.jdbc; @@ -27,8 +25,8 @@ public final class Db2ServerConfig extends AbstractDbConfig { @Override protected void doStartDb() { db2 = new Db2Container() - .acceptLicense() - .withLogConsumer(outputFrame -> logger.debug(outputFrame.getUtf8String())); + .acceptLicense() + .withLogConsumer(outputFrame -> logger.debug(outputFrame.getUtf8String())); db2.start(); } @@ -40,7 +38,6 @@ protected void doShutdownDb() { @Override public String getJdbcUrl() { return db2.getJdbcUrl(); - } @Override diff --git a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/DbConfig.java b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/DbConfig.java index 964722220..2926b610b 100644 --- a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/DbConfig.java +++ b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/DbConfig.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support.jdbc; diff --git a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/H2Config.java b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/H2Config.java index cd0b73b38..5f744ed17 100644 --- a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/H2Config.java +++ b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/H2Config.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support.jdbc; diff --git a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/HsqlConfig.java b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/HsqlConfig.java index 86e7db460..565cb2037 100644 --- a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/HsqlConfig.java +++ b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/HsqlConfig.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support.jdbc; diff --git a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/JdbcTestUtils.java b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/JdbcTestUtils.java index 834c05ede..8b9998b13 100644 --- a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/JdbcTestUtils.java +++ b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/JdbcTestUtils.java @@ -1,25 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support.jdbc; -import org.springframework.jdbc.core.JdbcTemplate; - -import javax.sql.DataSource; import java.sql.Timestamp; import java.time.Instant; +import javax.sql.DataSource; +import org.springframework.jdbc.core.JdbcTemplate; public final class JdbcTestUtils { @@ -38,11 +35,16 @@ public Timestamp getLockedUntil(String lockName) { } public LockInfo getLockInfo(String lockName) { - return jdbcTemplate.query("SELECT name, lock_until, " + dbConfig.nowExpression() + " as db_time FROM shedlock WHERE name = ?", (rs, rowNum) -> new LockInfo( - rs.getString("name"), - rs.getTimestamp("lock_until").toInstant(), - rs.getTimestamp("db_time").toInstant() - ), lockName).get(0); + return jdbcTemplate + .query( + "SELECT name, lock_until, " + dbConfig.nowExpression() + + " as db_time FROM shedlock WHERE name = ?", + (rs, rowNum) -> new LockInfo( + rs.getString("name"), + rs.getTimestamp("lock_until").toInstant(), + rs.getTimestamp("db_time").toInstant()), + lockName) + .get(0); } public void clean() { @@ -82,11 +84,7 @@ public Instant getDbTime() { @Override public String toString() { - return "LockInfo{" + - "name='" + name + '\'' + - ", lockUntil=" + lockUntil + - ", dbTime=" + dbTime + - '}'; + return "LockInfo{" + "name='" + name + '\'' + ", lockUntil=" + lockUntil + ", dbTime=" + dbTime + '}'; } } } diff --git a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/MariaDbConfig.java b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/MariaDbConfig.java index 3edd63d40..08f4569a9 100644 --- a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/MariaDbConfig.java +++ b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/MariaDbConfig.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support.jdbc; @@ -20,10 +18,9 @@ public class MariaDbConfig extends AbstractContainerBasedDbConfig { public MariaDbConfig() { super(new MyMariaDbContainer() - .withDatabaseName(TEST_SCHEMA_NAME) - .withUsername("SA") - .withPassword("pass") - ); + .withDatabaseName(TEST_SCHEMA_NAME) + .withUsername("SA") + .withPassword("pass")); } @Override @@ -36,6 +33,5 @@ public String nowExpression() { return "UTC_TIMESTAMP(3)"; } - static class MyMariaDbContainer extends MariaDBContainer { - } + static class MyMariaDbContainer extends MariaDBContainer {} } diff --git a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/MsSqlServerConfig.java b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/MsSqlServerConfig.java index 64b852389..382cfbd30 100644 --- a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/MsSqlServerConfig.java +++ b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/MsSqlServerConfig.java @@ -1,26 +1,24 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support.jdbc; +import static org.testcontainers.containers.MSSQLServerContainer.MS_SQL_SERVER_PORT; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.MSSQLServerContainer; -import static org.testcontainers.containers.MSSQLServerContainer.MS_SQL_SERVER_PORT; - public final class MsSqlServerConfig extends AbstractContainerBasedDbConfig { private static final Logger LOGGER = LoggerFactory.getLogger(MsSqlServerConfig.class); diff --git a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/MySqlConfig.java b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/MySqlConfig.java index 824dfdc18..dcf91a1b5 100644 --- a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/MySqlConfig.java +++ b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/MySqlConfig.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support.jdbc; @@ -20,11 +18,10 @@ public class MySqlConfig extends AbstractContainerBasedDbConfig { public MySqlConfig() { super(new MyMySQLContainer() - .withDatabaseName(TEST_SCHEMA_NAME) - .withUsername("SA") - .withPassword("pass") - .withCommand("--default-authentication-plugin=mysql_native_password") - ); + .withDatabaseName(TEST_SCHEMA_NAME) + .withUsername("SA") + .withPassword("pass") + .withCommand("--default-authentication-plugin=mysql_native_password")); } @Override diff --git a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/OracleServerConfig.java b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/OracleServerConfig.java index a5329f6e1..4e5422fea 100644 --- a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/OracleServerConfig.java +++ b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/OracleServerConfig.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support.jdbc; @@ -36,5 +34,4 @@ public String nowExpression() { public String getR2dbcUrl() { return "r2dbc:oracle://localhost:" + container.getOraclePort() + "/" + container.getDatabaseName(); } - } diff --git a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/PostgresConfig.java b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/PostgresConfig.java index 941479311..ba0ca906d 100644 --- a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/PostgresConfig.java +++ b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/PostgresConfig.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support.jdbc; @@ -20,9 +18,9 @@ public class PostgresConfig extends AbstractContainerBasedDbConfig { public PostgresConfig() { super(new MyPostgreSQLContainer() - .withDatabaseName(TEST_SCHEMA_NAME) - .withUsername("SA") - .withPassword("pass")); + .withDatabaseName(TEST_SCHEMA_NAME) + .withUsername("SA") + .withPassword("pass")); } @Override diff --git a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/TransactionalFuzzTester.java b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/TransactionalFuzzTester.java index 2915ab5b7..e784d1e43 100644 --- a/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/TransactionalFuzzTester.java +++ b/providers/jdbc/shedlock-test-support-jdbc/src/main/java/net/javacrumbs/shedlock/test/support/jdbc/TransactionalFuzzTester.java @@ -1,35 +1,34 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support.jdbc; +import java.util.concurrent.ExecutionException; +import javax.sql.DataSource; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.test.support.FuzzTester; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.support.TransactionTemplate; -import javax.sql.DataSource; -import java.util.concurrent.ExecutionException; - public class TransactionalFuzzTester { - public static void fuzzTestShouldWorkWithTransaction(LockProvider lockProvider, DataSource dataSource) throws ExecutionException, InterruptedException { + public static void fuzzTestShouldWorkWithTransaction(LockProvider lockProvider, DataSource dataSource) + throws ExecutionException, InterruptedException { new FuzzTester(lockProvider) { @Override protected Void task(int iterations, Job job) { - TransactionTemplate transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + TransactionTemplate transactionTemplate = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); return transactionTemplate.execute(status -> super.task(iterations, job)); } diff --git a/providers/memcached/shedlock-provider-memcached-spy/src/main/java/net/javacrumbs/shedlock/provider/memcached/spy/MemcachedLockProvider.java b/providers/memcached/shedlock-provider-memcached-spy/src/main/java/net/javacrumbs/shedlock/provider/memcached/spy/MemcachedLockProvider.java index 8a9d5e974..c91fe8677 100644 --- a/providers/memcached/shedlock-provider-memcached-spy/src/main/java/net/javacrumbs/shedlock/provider/memcached/spy/MemcachedLockProvider.java +++ b/providers/memcached/shedlock-provider-memcached-spy/src/main/java/net/javacrumbs/shedlock/provider/memcached/spy/MemcachedLockProvider.java @@ -1,5 +1,11 @@ package net.javacrumbs.shedlock.provider.memcached.spy; +import static net.javacrumbs.shedlock.support.Utils.getHostname; +import static net.javacrumbs.shedlock.support.Utils.toIsoString; + +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; @@ -11,13 +17,6 @@ import net.spy.memcached.ops.OperationStatus; import net.spy.memcached.util.StringUtils; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; - -import static net.javacrumbs.shedlock.support.Utils.getHostname; -import static net.javacrumbs.shedlock.support.Utils.toIsoString; - /** * Lock Provider for Memcached * @@ -25,14 +24,10 @@ */ public class MemcachedLockProvider implements LockProvider { - /** - * KEY PREFIX - */ + /** KEY PREFIX */ private static final String KEY_PREFIX = "shedlock"; - /** - * ENV DEFAULT - */ + /** ENV DEFAULT */ private static final String ENV_DEFAULT = "default"; private final MemcachedClient client; @@ -41,26 +36,31 @@ public class MemcachedLockProvider implements LockProvider { /** * Create MemcachedLockProvider - * @param client Spy.memcached.MemcachedClient + * + * @param client + * Spy.memcached.MemcachedClient */ - public MemcachedLockProvider(@NonNull MemcachedClient client){ + public MemcachedLockProvider(@NonNull MemcachedClient client) { this(client, ENV_DEFAULT); } /** * Create MemcachedLockProvider - * @param client Spy.memcached.MemcachedClient - * @param env is part of the key and thus makes sure there is not key conflict between multiple ShedLock instances - * running on the same memcached + * + * @param client + * Spy.memcached.MemcachedClient + * @param env + * is part of the key and thus makes sure there is not key conflict + * between multiple ShedLock instances running on the same memcached */ - public MemcachedLockProvider(@NonNull MemcachedClient client, @NonNull String env){ + public MemcachedLockProvider(@NonNull MemcachedClient client, @NonNull String env) { this.client = client; this.env = env; } @Override @NonNull - public Optional lock(@NonNull LockConfiguration lockConfiguration){ + public Optional lock(@NonNull LockConfiguration lockConfiguration) { long expireTime = getSecondUntil(lockConfiguration.getLockAtMostUntil()); String key = buildKey(lockConfiguration.getName(), this.env); OperationStatus status = client.add(key, (int) expireTime, buildValue()).getStatus(); @@ -70,10 +70,9 @@ public Optional lock(@NonNull LockConfiguration lockConfiguration){ return Optional.empty(); } - private static long getSecondUntil(Instant instant) { long millis = Duration.between(ClockProvider.now(), instant).toMillis(); - return millis / 1000; + return millis / 1000; } static String buildKey(String lockName, String env) { @@ -86,16 +85,14 @@ private static String buildValue() { return String.format("ADDED:%s@%s", toIsoString(ClockProvider.now()), getHostname()); } - private static final class MemcachedLock extends AbstractSimpleLock { private final String key; private final MemcachedClient client; - private MemcachedLock(@NonNull String key, - @NonNull MemcachedClient client, - @NonNull LockConfiguration lockConfiguration) { + private MemcachedLock( + @NonNull String key, @NonNull MemcachedClient client, @NonNull LockConfiguration lockConfiguration) { super(lockConfiguration); this.key = key; this.client = client; @@ -110,12 +107,12 @@ protected void doUnlock() { throw new LockException("Can not remove node. " + status.getMessage()); } } else { - OperationStatus status = client.replace(key, (int) keepLockFor, buildValue()).getStatus(); + OperationStatus status = + client.replace(key, (int) keepLockFor, buildValue()).getStatus(); if (!status.isSuccess()) { throw new LockException("Can not replace node. " + status.getMessage()); } } } } - } diff --git a/providers/memcached/shedlock-provider-memcached-spy/src/test/java/net/javacrumbs/shedlock/provider/memcached/spy/MemcachedContainer.java b/providers/memcached/shedlock-provider-memcached-spy/src/test/java/net/javacrumbs/shedlock/provider/memcached/spy/MemcachedContainer.java index e914c91bc..bddb45d8c 100644 --- a/providers/memcached/shedlock-provider-memcached-spy/src/test/java/net/javacrumbs/shedlock/provider/memcached/spy/MemcachedContainer.java +++ b/providers/memcached/shedlock-provider-memcached-spy/src/test/java/net/javacrumbs/shedlock/provider/memcached/spy/MemcachedContainer.java @@ -13,8 +13,6 @@ public class MemcachedContainer extends GenericContainer { public MemcachedContainer() { super(MEMCACHED_IMAGE.asCanonicalNameString()); - this.withExposedPorts(11211) - .withLogConsumer(frame -> LOGGER.info(frame.getUtf8String())); + this.withExposedPorts(11211).withLogConsumer(frame -> LOGGER.info(frame.getUtf8String())); } - } diff --git a/providers/memcached/shedlock-provider-memcached-spy/src/test/java/net/javacrumbs/shedlock/provider/memcached/spy/MemcachedLockProviderIntegrationTest.java b/providers/memcached/shedlock-provider-memcached-spy/src/test/java/net/javacrumbs/shedlock/provider/memcached/spy/MemcachedLockProviderIntegrationTest.java index ee238dc2c..9cd9566b3 100644 --- a/providers/memcached/shedlock-provider-memcached-spy/src/test/java/net/javacrumbs/shedlock/provider/memcached/spy/MemcachedLockProviderIntegrationTest.java +++ b/providers/memcached/shedlock-provider-memcached-spy/src/test/java/net/javacrumbs/shedlock/provider/memcached/spy/MemcachedLockProviderIntegrationTest.java @@ -1,5 +1,11 @@ package net.javacrumbs.shedlock.provider.memcached.spy; +import static java.lang.Thread.sleep; +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.time.Duration; +import java.util.Optional; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.SimpleLock; @@ -11,14 +17,6 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import java.io.IOException; -import java.time.Duration; -import java.util.Optional; - -import static java.lang.Thread.sleep; -import static org.assertj.core.api.Assertions.assertThat; - - @Testcontainers public class MemcachedLockProviderIntegrationTest extends AbstractLockProviderIntegrationTest { @@ -34,13 +32,11 @@ public class MemcachedLockProviderIntegrationTest extends AbstractLockProviderIn @BeforeEach public void createLockProvider() throws IOException { memcachedClient = new MemcachedClient( - AddrUtil.getAddresses(container.getContainerIpAddress() + ":" + container.getFirstMappedPort()) - ); + AddrUtil.getAddresses(container.getContainerIpAddress() + ":" + container.getFirstMappedPort())); lockProvider = new MemcachedLockProvider(memcachedClient, ENV); } - @Override protected void assertUnlocked(String lockName) { assertThat(getLock(lockName)).isNull(); @@ -51,16 +47,13 @@ protected void assertLocked(String lockName) { assertThat(getLock(lockName)).isNotNull(); } - @Override @Test public void shouldTimeout() throws InterruptedException { this.doTestTimeout(Duration.ofSeconds(1)); } - /** - * memcached smallest unit is second. - */ + /** memcached smallest unit is second. */ @Override protected void doTestTimeout(Duration lockAtMostFor) throws InterruptedException { LockConfiguration configWithShortTimeout = lockConfig(LOCK_NAME1, lockAtMostFor, Duration.ZERO); @@ -70,12 +63,12 @@ protected void doTestTimeout(Duration lockAtMostFor) throws InterruptedException sleep(lockAtMostFor.toMillis() * 2); assertUnlocked(LOCK_NAME1); - Optional lock2 = getLockProvider().lock(lockConfig(LOCK_NAME1, Duration.ofSeconds(1), Duration.ZERO)); + Optional lock2 = + getLockProvider().lock(lockConfig(LOCK_NAME1, Duration.ofSeconds(1), Duration.ZERO)); assertThat(lock2).isNotEmpty(); lock2.get().unlock(); } - @Override protected LockProvider getLockProvider() { return lockProvider; @@ -84,5 +77,4 @@ protected LockProvider getLockProvider() { private String getLock(String lockName) { return (String) memcachedClient.get(MemcachedLockProvider.buildKey(lockName, ENV)); } - } diff --git a/providers/mongo/shedlock-provider-mongo-reactivestreams/src/main/java/net/javacrumbs/shedlock/provider/mongo/reactivestreams/ReactiveStreamsMongoLockProvider.java b/providers/mongo/shedlock-provider-mongo-reactivestreams/src/main/java/net/javacrumbs/shedlock/provider/mongo/reactivestreams/ReactiveStreamsMongoLockProvider.java index 80fe13774..84b6393a0 100644 --- a/providers/mongo/shedlock-provider-mongo-reactivestreams/src/main/java/net/javacrumbs/shedlock/provider/mongo/reactivestreams/ReactiveStreamsMongoLockProvider.java +++ b/providers/mongo/shedlock-provider-mongo-reactivestreams/src/main/java/net/javacrumbs/shedlock/provider/mongo/reactivestreams/ReactiveStreamsMongoLockProvider.java @@ -1,24 +1,31 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.mongo.reactivestreams; +import static com.mongodb.client.model.Filters.and; +import static com.mongodb.client.model.Filters.eq; +import static com.mongodb.client.model.Filters.gt; +import static com.mongodb.client.model.Filters.lte; +import static com.mongodb.client.model.Updates.combine; +import static com.mongodb.client.model.Updates.set; + import com.mongodb.MongoServerException; import com.mongodb.client.model.FindOneAndUpdateOptions; import com.mongodb.reactivestreams.client.MongoCollection; import com.mongodb.reactivestreams.client.MongoDatabase; +import java.time.Instant; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.ExtensibleLockProvider; @@ -31,20 +38,13 @@ import org.bson.conversions.Bson; import org.reactivestreams.Publisher; -import java.time.Instant; -import java.util.Optional; - -import static com.mongodb.client.model.Filters.and; -import static com.mongodb.client.model.Filters.eq; -import static com.mongodb.client.model.Filters.gt; -import static com.mongodb.client.model.Filters.lte; -import static com.mongodb.client.model.Updates.combine; -import static com.mongodb.client.model.Updates.set; - /** - * Distributed lock using Reactive MongoDB. Requires mongodb-driver-reactivestreams + * Distributed lock using Reactive MongoDB. Requires + * mongodb-driver-reactivestreams + * *

* It uses a collection that contains documents like this: + * *

  * {
  *    "_id" : "lock name",
@@ -54,22 +54,18 @@
  * }
  * 
* - * lockedAt and lockedBy are just for troubleshooting and are not read by the code + * lockedAt and lockedBy are just for troubleshooting and are not read by the + * code * *
    - *
  1. - * Attempts to insert a new lock record. As an optimization, we keep in-memory track of created lock records. If the record - * has been inserted, returns lock. - *
  2. - *
  3. - * We will try to update lock record using filter _id == name AND lock_until <= now - *
  4. - *
  5. - * If the update succeeded (1 updated document), we have the lock. If the update failed (0 updated documents) somebody else holds the lock - *
  6. - *
  7. - * When unlocking, lock_until is set to now. - *
  8. + *
  9. Attempts to insert a new lock record. As an optimization, we keep + * in-memory track of created lock records. If the record has been inserted, + * returns lock. + *
  10. We will try to update lock record using filter _id == name AND lock_until + * <= now + *
  11. If the update succeeded (1 updated document), we have the lock. If the + * update failed (0 updated documents) somebody else holds the lock + *
  12. When unlocking, lock_until is set to now. *
*/ public class ReactiveStreamsMongoLockProvider implements ExtensibleLockProvider { @@ -82,9 +78,7 @@ public class ReactiveStreamsMongoLockProvider implements ExtensibleLockProvider private final String hostname; private final MongoCollection collection; - /** - * Uses Mongo to coordinate locks - */ + /** Uses Mongo to coordinate locks */ public ReactiveStreamsMongoLockProvider(MongoDatabase mongoDatabase) { this(mongoDatabase.getCollection(DEFAULT_SHEDLOCK_COLLECTION_NAME)); } @@ -92,37 +86,36 @@ public ReactiveStreamsMongoLockProvider(MongoDatabase mongoDatabase) { /** * Uses Mongo to coordinate locks * - * @param collection Mongo collection to be used + * @param collection + * Mongo collection to be used */ public ReactiveStreamsMongoLockProvider(MongoCollection collection) { this.collection = collection; this.hostname = Utils.getHostname(); } - @Override public Optional lock(LockConfiguration lockConfiguration) { Instant now = now(); Bson update = combine( - set(LOCK_UNTIL, lockConfiguration.getLockAtMostUntil()), - set(LOCKED_AT, now), - set(LOCKED_BY, hostname) - ); + set(LOCK_UNTIL, lockConfiguration.getLockAtMostUntil()), set(LOCKED_AT, now), set(LOCKED_BY, hostname)); try { // There are three possible situations: // 1. The lock document does not exist yet - it is inserted - we have the lock - // 2. The lock document exists and lockUtil <= now - it is updated - we have the lock - // 3. The lock document exists and lockUtil > now - Duplicate key exception is thrown - execute(getCollection().findOneAndUpdate( - and(eq(ID, lockConfiguration.getName()), lte(LOCK_UNTIL, now)), - update, - new FindOneAndUpdateOptions().upsert(true) - )); + // 2. The lock document exists and lockUtil <= now - it is updated - we have the + // lock + // 3. The lock document exists and lockUtil > now - Duplicate key exception is + // thrown + execute(getCollection() + .findOneAndUpdate( + and(eq(ID, lockConfiguration.getName()), lte(LOCK_UNTIL, now)), + update, + new FindOneAndUpdateOptions().upsert(true))); return Optional.of(new ReactiveMongoLock(lockConfiguration, this)); } catch (MongoServerException e) { if (e.getCode() == 11000) { // duplicate key - //Upsert attempts to insert when there were no filter matches. - //This means there was a lock with matching ID with lockUntil > now. + // Upsert attempts to insert when there were no filter matches. + // This means there was a lock with matching ID with lockUntil > now. return Optional.empty(); } else { throw e; @@ -134,14 +127,10 @@ private Optional extend(LockConfiguration lockConfiguration) { Instant now = now(); Bson update = set(LOCK_UNTIL, lockConfiguration.getLockAtMostUntil()); - Document updatedDocument = execute(getCollection().findOneAndUpdate( - and( - eq(ID, lockConfiguration.getName()), - gt(LOCK_UNTIL, now), - eq(LOCKED_BY, hostname) - ), - update - )); + Document updatedDocument = execute(getCollection() + .findOneAndUpdate( + and(eq(ID, lockConfiguration.getName()), gt(LOCK_UNTIL, now), eq(LOCKED_BY, hostname)), + update)); if (updatedDocument != null) { return Optional.of(new ReactiveMongoLock(lockConfiguration, this)); @@ -152,10 +141,10 @@ private Optional extend(LockConfiguration lockConfiguration) { private void unlock(LockConfiguration lockConfiguration) { // Set lockUtil to now or lockAtLeastUntil whichever is later - execute(getCollection().findOneAndUpdate( - eq(ID, lockConfiguration.getName()), - combine(set(LOCK_UNTIL, lockConfiguration.getUnlockTime())) - )); + execute(getCollection() + .findOneAndUpdate( + eq(ID, lockConfiguration.getName()), + combine(set(LOCK_UNTIL, lockConfiguration.getUnlockTime())))); } @Nullable @@ -186,7 +175,8 @@ private Instant now() { private static final class ReactiveMongoLock extends AbstractSimpleLock { private final ReactiveStreamsMongoLockProvider mongoLockProvider; - private ReactiveMongoLock(LockConfiguration lockConfiguration, ReactiveStreamsMongoLockProvider mongoLockProvider) { + private ReactiveMongoLock( + LockConfiguration lockConfiguration, ReactiveStreamsMongoLockProvider mongoLockProvider) { super(lockConfiguration); this.mongoLockProvider = mongoLockProvider; } diff --git a/providers/mongo/shedlock-provider-mongo-reactivestreams/src/main/java/net/javacrumbs/shedlock/provider/mongo/reactivestreams/SingleLockableSubscriber.java b/providers/mongo/shedlock-provider-mongo-reactivestreams/src/main/java/net/javacrumbs/shedlock/provider/mongo/reactivestreams/SingleLockableSubscriber.java index f1359b129..082c07f04 100644 --- a/providers/mongo/shedlock-provider-mongo-reactivestreams/src/main/java/net/javacrumbs/shedlock/provider/mongo/reactivestreams/SingleLockableSubscriber.java +++ b/providers/mongo/shedlock-provider-mongo-reactivestreams/src/main/java/net/javacrumbs/shedlock/provider/mongo/reactivestreams/SingleLockableSubscriber.java @@ -1,30 +1,28 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.mongo.reactivestreams; -import net.javacrumbs.shedlock.support.annotation.Nullable; -import org.reactivestreams.Subscriber; -import org.reactivestreams.Subscription; - import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import net.javacrumbs.shedlock.support.annotation.Nullable; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; /** - * Subscriber that expects a single result and allows locking until complete or error + * Subscriber that expects a single result and allows locking until complete or + * error * * @param */ diff --git a/providers/mongo/shedlock-provider-mongo-reactivestreams/src/test/java/net/javacrumbs/shedlock/provider/mongo/reactivestreams/ReactiveStreamsMongoLockProviderIntegrationTest.java b/providers/mongo/shedlock-provider-mongo-reactivestreams/src/test/java/net/javacrumbs/shedlock/provider/mongo/reactivestreams/ReactiveStreamsMongoLockProviderIntegrationTest.java index 662daec63..e8dd0179c 100644 --- a/providers/mongo/shedlock-provider-mongo-reactivestreams/src/test/java/net/javacrumbs/shedlock/provider/mongo/reactivestreams/ReactiveStreamsMongoLockProviderIntegrationTest.java +++ b/providers/mongo/shedlock-provider-mongo-reactivestreams/src/test/java/net/javacrumbs/shedlock/provider/mongo/reactivestreams/ReactiveStreamsMongoLockProviderIntegrationTest.java @@ -1,20 +1,28 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.mongo.reactivestreams; +import static com.mongodb.client.model.Filters.eq; +import static net.javacrumbs.shedlock.provider.mongo.reactivestreams.ReactiveStreamsMongoLockProvider.DEFAULT_SHEDLOCK_COLLECTION_NAME; +import static net.javacrumbs.shedlock.provider.mongo.reactivestreams.ReactiveStreamsMongoLockProvider.ID; +import static net.javacrumbs.shedlock.provider.mongo.reactivestreams.ReactiveStreamsMongoLockProvider.LOCKED_AT; +import static net.javacrumbs.shedlock.provider.mongo.reactivestreams.ReactiveStreamsMongoLockProvider.LOCKED_BY; +import static net.javacrumbs.shedlock.provider.mongo.reactivestreams.ReactiveStreamsMongoLockProvider.LOCK_UNTIL; +import static net.javacrumbs.shedlock.provider.mongo.reactivestreams.ReactiveStreamsMongoLockProvider.execute; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assumptions.assumeThat; + import com.mongodb.client.result.DeleteResult; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; @@ -24,6 +32,8 @@ import de.flapdoodle.embed.mongo.MongodStarter; import de.flapdoodle.embed.mongo.config.MongodConfig; import de.flapdoodle.embed.mongo.distribution.Version; +import java.io.IOException; +import java.util.Date; import net.javacrumbs.shedlock.core.ExtensibleLockProvider; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.test.support.AbstractExtensibleLockProviderIntegrationTest; @@ -33,19 +43,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.IOException; -import java.util.Date; - -import static com.mongodb.client.model.Filters.eq; -import static net.javacrumbs.shedlock.provider.mongo.reactivestreams.ReactiveStreamsMongoLockProvider.DEFAULT_SHEDLOCK_COLLECTION_NAME; -import static net.javacrumbs.shedlock.provider.mongo.reactivestreams.ReactiveStreamsMongoLockProvider.ID; -import static net.javacrumbs.shedlock.provider.mongo.reactivestreams.ReactiveStreamsMongoLockProvider.LOCKED_AT; -import static net.javacrumbs.shedlock.provider.mongo.reactivestreams.ReactiveStreamsMongoLockProvider.LOCKED_BY; -import static net.javacrumbs.shedlock.provider.mongo.reactivestreams.ReactiveStreamsMongoLockProvider.LOCK_UNTIL; -import static net.javacrumbs.shedlock.provider.mongo.reactivestreams.ReactiveStreamsMongoLockProvider.execute; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assumptions.assumeThat; - public class ReactiveStreamsMongoLockProviderIntegrationTest extends AbstractExtensibleLockProviderIntegrationTest { private static final MongodStarter starter = MongodStarter.getDefaultInstance(); @@ -58,12 +55,12 @@ public class ReactiveStreamsMongoLockProviderIntegrationTest extends AbstractExt @BeforeAll public static void startMongo() throws IOException { - mongodExe = starter.prepare(MongodConfig.builder() - .version(Version.Main.V3_6) - .build()); + mongodExe = starter.prepare( + MongodConfig.builder().version(Version.Main.V3_6).build()); mongod = mongodExe.start(); - mongo = MongoClients.create("mongodb://localhost:" + mongod.getConfig().net().getPort()); + mongo = MongoClients.create( + "mongodb://localhost:" + mongod.getConfig().net().getPort()); } @AfterAll @@ -73,7 +70,6 @@ public static void stopMongo() { mongodExe.stop(); } - @BeforeEach public void cleanDb() { execute(mongo.getDatabase(DB_NAME).drop()); diff --git a/providers/mongo/shedlock-provider-mongo/src/main/java/net/javacrumbs/shedlock/provider/mongo/MongoLockProvider.java b/providers/mongo/shedlock-provider-mongo/src/main/java/net/javacrumbs/shedlock/provider/mongo/MongoLockProvider.java index e41f0cb65..d4861b6b1 100644 --- a/providers/mongo/shedlock-provider-mongo/src/main/java/net/javacrumbs/shedlock/provider/mongo/MongoLockProvider.java +++ b/providers/mongo/shedlock-provider-mongo/src/main/java/net/javacrumbs/shedlock/provider/mongo/MongoLockProvider.java @@ -1,24 +1,31 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.mongo; +import static com.mongodb.client.model.Filters.and; +import static com.mongodb.client.model.Filters.eq; +import static com.mongodb.client.model.Filters.gt; +import static com.mongodb.client.model.Filters.lte; +import static com.mongodb.client.model.Updates.combine; +import static com.mongodb.client.model.Updates.set; + import com.mongodb.MongoServerException; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.FindOneAndUpdateOptions; +import java.time.Instant; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.ExtensibleLockProvider; @@ -28,20 +35,13 @@ import org.bson.Document; import org.bson.conversions.Bson; -import java.time.Instant; -import java.util.Optional; - -import static com.mongodb.client.model.Filters.and; -import static com.mongodb.client.model.Filters.eq; -import static com.mongodb.client.model.Filters.gt; -import static com.mongodb.client.model.Filters.lte; -import static com.mongodb.client.model.Updates.combine; -import static com.mongodb.client.model.Updates.set; - /** - * Distributed lock using MongoDB >= 2.6. Requires mongo-java-driver > 3.4.0 + * Distributed lock using MongoDB >= 2.6. Requires mongo-java-driver > + * 3.4.0 + * *

* It uses a collection that contains documents like this: + * *

  * {
  *    "_id" : "lock name",
@@ -51,22 +51,18 @@
  * }
  * 
* - * lockedAt and lockedBy are just for troubleshooting and are not read by the code + * lockedAt and lockedBy are just for troubleshooting and are not read by the + * code * *
    - *
  1. - * Attempts to insert a new lock record. As an optimization, we keep in-memory track of created lock records. If the record - * has been inserted, returns lock. - *
  2. - *
  3. - * We will try to update lock record using filter _id == name AND lock_until <= now - *
  4. - *
  5. - * If the update succeeded (1 updated document), we have the lock. If the update failed (0 updated documents) somebody else holds the lock - *
  6. - *
  7. - * When unlocking, lock_until is set to now. - *
  8. + *
  9. Attempts to insert a new lock record. As an optimization, we keep + * in-memory track of created lock records. If the record has been inserted, + * returns lock. + *
  10. We will try to update lock record using filter _id == name AND lock_until + * <= now + *
  11. If the update succeeded (1 updated document), we have the lock. If the + * update failed (0 updated documents) somebody else holds the lock + *
  12. When unlocking, lock_until is set to now. *
*/ public class MongoLockProvider implements ExtensibleLockProvider { @@ -79,9 +75,7 @@ public class MongoLockProvider implements ExtensibleLockProvider { private final String hostname; private final MongoCollection collection; - /** - * Uses Mongo to coordinate locks - */ + /** Uses Mongo to coordinate locks */ public MongoLockProvider(MongoDatabase mongoDatabase) { this(mongoDatabase.getCollection(DEFAULT_SHEDLOCK_COLLECTION_NAME)); } @@ -89,37 +83,36 @@ public MongoLockProvider(MongoDatabase mongoDatabase) { /** * Uses Mongo to coordinate locks * - * @param collection Mongo collection to be used + * @param collection + * Mongo collection to be used */ public MongoLockProvider(MongoCollection collection) { this.collection = collection; this.hostname = Utils.getHostname(); } - @Override public Optional lock(LockConfiguration lockConfiguration) { Instant now = now(); Bson update = combine( - set(LOCK_UNTIL, lockConfiguration.getLockAtMostUntil()), - set(LOCKED_AT, now), - set(LOCKED_BY, hostname) - ); + set(LOCK_UNTIL, lockConfiguration.getLockAtMostUntil()), set(LOCKED_AT, now), set(LOCKED_BY, hostname)); try { // There are three possible situations: // 1. The lock document does not exist yet - it is inserted - we have the lock - // 2. The lock document exists and lockUtil <= now - it is updated - we have the lock - // 3. The lock document exists and lockUtil > now - Duplicate key exception is thrown - getCollection().findOneAndUpdate( - and(eq(ID, lockConfiguration.getName()), lte(LOCK_UNTIL, now)), - update, - new FindOneAndUpdateOptions().upsert(true) - ); + // 2. The lock document exists and lockUtil <= now - it is updated - we have the + // lock + // 3. The lock document exists and lockUtil > now - Duplicate key exception is + // thrown + getCollection() + .findOneAndUpdate( + and(eq(ID, lockConfiguration.getName()), lte(LOCK_UNTIL, now)), + update, + new FindOneAndUpdateOptions().upsert(true)); return Optional.of(new MongoLock(lockConfiguration, this)); } catch (MongoServerException e) { if (e.getCode() == 11000) { // duplicate key - //Upsert attempts to insert when there were no filter matches. - //This means there was a lock with matching ID with lockUntil > now. + // Upsert attempts to insert when there were no filter matches. + // This means there was a lock with matching ID with lockUntil > now. return Optional.empty(); } else { throw e; @@ -131,14 +124,9 @@ private Optional extend(LockConfiguration lockConfiguration) { Instant now = now(); Bson update = set(LOCK_UNTIL, lockConfiguration.getLockAtMostUntil()); - Document updatedDocument = getCollection().findOneAndUpdate( - and( - eq(ID, lockConfiguration.getName()), - gt(LOCK_UNTIL, now), - eq(LOCKED_BY, hostname) - ), - update - ); + Document updatedDocument = getCollection() + .findOneAndUpdate( + and(eq(ID, lockConfiguration.getName()), gt(LOCK_UNTIL, now), eq(LOCKED_BY, hostname)), update); if (updatedDocument != null) { return Optional.of(new MongoLock(lockConfiguration, this)); } else { @@ -148,10 +136,10 @@ private Optional extend(LockConfiguration lockConfiguration) { private void unlock(LockConfiguration lockConfiguration) { // Set lockUtil to now or lockAtLeastUntil whichever is later - getCollection().findOneAndUpdate( - eq(ID, lockConfiguration.getName()), - combine(set(LOCK_UNTIL, lockConfiguration.getUnlockTime())) - ); + getCollection() + .findOneAndUpdate( + eq(ID, lockConfiguration.getName()), + combine(set(LOCK_UNTIL, lockConfiguration.getUnlockTime()))); } private MongoCollection getCollection() { diff --git a/providers/mongo/shedlock-provider-mongo/src/test/java/net/javacrumbs/shedlock/provider/mongo/MongoLockProviderIntegrationTest.java b/providers/mongo/shedlock-provider-mongo/src/test/java/net/javacrumbs/shedlock/provider/mongo/MongoLockProviderIntegrationTest.java index c211ae423..60ef6fd23 100644 --- a/providers/mongo/shedlock-provider-mongo/src/test/java/net/javacrumbs/shedlock/provider/mongo/MongoLockProviderIntegrationTest.java +++ b/providers/mongo/shedlock-provider-mongo/src/test/java/net/javacrumbs/shedlock/provider/mongo/MongoLockProviderIntegrationTest.java @@ -1,20 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.mongo; +import static com.mongodb.client.model.Filters.eq; +import static net.javacrumbs.shedlock.provider.mongo.MongoLockProvider.DEFAULT_SHEDLOCK_COLLECTION_NAME; +import static net.javacrumbs.shedlock.provider.mongo.MongoLockProvider.ID; +import static net.javacrumbs.shedlock.provider.mongo.MongoLockProvider.LOCKED_AT; +import static net.javacrumbs.shedlock.provider.mongo.MongoLockProvider.LOCKED_BY; +import static net.javacrumbs.shedlock.provider.mongo.MongoLockProvider.LOCK_UNTIL; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assumptions.assumeThat; + import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; @@ -24,6 +31,8 @@ import de.flapdoodle.embed.mongo.MongodStarter; import de.flapdoodle.embed.mongo.config.MongodConfig; import de.flapdoodle.embed.mongo.distribution.Version; +import java.io.IOException; +import java.util.Date; import net.javacrumbs.shedlock.core.ExtensibleLockProvider; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.test.support.AbstractExtensibleLockProviderIntegrationTest; @@ -33,18 +42,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.IOException; -import java.util.Date; - -import static com.mongodb.client.model.Filters.eq; -import static net.javacrumbs.shedlock.provider.mongo.MongoLockProvider.DEFAULT_SHEDLOCK_COLLECTION_NAME; -import static net.javacrumbs.shedlock.provider.mongo.MongoLockProvider.ID; -import static net.javacrumbs.shedlock.provider.mongo.MongoLockProvider.LOCKED_AT; -import static net.javacrumbs.shedlock.provider.mongo.MongoLockProvider.LOCKED_BY; -import static net.javacrumbs.shedlock.provider.mongo.MongoLockProvider.LOCK_UNTIL; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assumptions.assumeThat; - public class MongoLockProviderIntegrationTest extends AbstractExtensibleLockProviderIntegrationTest { private static final MongodStarter starter = MongodStarter.getDefaultInstance(); @@ -57,12 +54,12 @@ public class MongoLockProviderIntegrationTest extends AbstractExtensibleLockProv @BeforeAll public static void startMongo() throws IOException { - mongodExe = starter.prepare(MongodConfig.builder() - .version(Version.Main.V3_6) - .build()); + mongodExe = starter.prepare( + MongodConfig.builder().version(Version.Main.V3_6).build()); mongod = mongodExe.start(); - mongo = MongoClients.create("mongodb://localhost:"+mongod.getConfig().net().getPort()); + mongo = MongoClients.create( + "mongodb://localhost:" + mongod.getConfig().net().getPort()); } @AfterAll @@ -72,7 +69,6 @@ public static void stopMongo() { mongodExe.stop(); } - @BeforeEach public void cleanDb() { mongo.getDatabase(DB_NAME).drop(); diff --git a/providers/neo4j/shedlock-provider-neo4j/src/main/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jLockProvider.java b/providers/neo4j/shedlock-provider-neo4j/src/main/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jLockProvider.java index 16a0bba97..00c27058a 100644 --- a/providers/neo4j/shedlock-provider-neo4j/src/main/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jLockProvider.java +++ b/providers/neo4j/shedlock-provider-neo4j/src/main/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jLockProvider.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.neo4j; @@ -21,27 +19,23 @@ import org.neo4j.driver.Driver; /** - * Lock provided by Neo4j Graph API. It uses a collection that stores each lock as a node. + * Lock provided by Neo4j Graph API. It uses a collection that stores each lock + * as a node. + * *

    - *
  1. - * Attempts to insert a new lock node. Since lock name has a unique constraint, it fails if the record already exists. - * As an optimization, we keep in-memory track of created lock nodes. - *
  2. - *
  3. - * If the insert succeeds (1 node inserted) we have the lock. - *
  4. - *
  5. - * If the insert failed due to duplicate key or we have skipped the insertion, we will try to update lock node using - * MATCH (lock:collectionName) WHERE name = $lockName AND lock_until <= $now SET lock_until = $lockUntil, locked_at = $now - * with some additional explicit node locking - *
  6. - *
  7. - * If the update succeeded (>1 property updated), we have the lock. If the update failed (<=1 properties updated) somebody else holds the lock - * or grabbed the lock in a data race caused by Neo4j's read-committed isolation level. - *
  8. - *
  9. - * When unlocking, lock_until is set to now. - *
  10. + *
  11. Attempts to insert a new lock node. Since lock name has a unique + * constraint, it fails if the record already exists. As an optimization, we + * keep in-memory track of created lock nodes. + *
  12. If the insert succeeds (1 node inserted) we have the lock. + *
  13. If the insert failed due to duplicate key or we have skipped the + * insertion, we will try to update lock node using MATCH (lock:collectionName) + * WHERE name = $lockName AND lock_until <= $now SET lock_until = $lockUntil, + * locked_at = $now with some additional explicit node locking + *
  14. If the update succeeded (>1 property updated), we have the lock. If + * the update failed (<=1 properties updated) somebody else holds the lock or + * grabbed the lock in a data race caused by Neo4j's read-committed isolation + * level. + *
  15. When unlocking, lock_until is set to now. *
*/ public class Neo4jLockProvider extends StorageBasedLockProvider { @@ -49,7 +43,8 @@ public Neo4jLockProvider(@NonNull Driver driver) { this(driver, "shedlock", null); } - public Neo4jLockProvider(@NonNull Driver graphDatabaseService, @NonNull String collectionName, @Nullable String databaseName) { + public Neo4jLockProvider( + @NonNull Driver graphDatabaseService, @NonNull String collectionName, @Nullable String databaseName) { super(new Neo4jStorageAccessor(graphDatabaseService, collectionName, databaseName)); } } diff --git a/providers/neo4j/shedlock-provider-neo4j/src/main/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jStorageAccessor.java b/providers/neo4j/shedlock-provider-neo4j/src/main/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jStorageAccessor.java index 46b959d62..5e69323f1 100644 --- a/providers/neo4j/shedlock-provider-neo4j/src/main/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jStorageAccessor.java +++ b/providers/neo4j/shedlock-provider-neo4j/src/main/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jStorageAccessor.java @@ -1,20 +1,23 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.neo4j; +import static java.util.Objects.requireNonNull; + +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.support.AbstractStorageAccessor; @@ -27,12 +30,6 @@ import org.neo4j.driver.SessionConfig; import org.neo4j.driver.Transaction; -import java.util.Map; -import java.util.function.BiFunction; -import java.util.function.Function; - -import static java.util.Objects.requireNonNull; - class Neo4jStorageAccessor extends AbstractStorageAccessor { private final String collectionName; private final Driver driver; @@ -46,11 +43,11 @@ public Neo4jStorageAccessor(@NonNull Driver driver, @NonNull String collectionNa } private void createLockNameUniqueConstraint() { - try ( - Session session = getSession(); - Transaction transaction = session.beginTransaction() - ) { - transaction.run(String.format("CREATE CONSTRAINT UNIQUE_%s_name IF NOT EXISTS ON (lock:%s) ASSERT lock.name IS UNIQUE", collectionName, collectionName)); + try (Session session = getSession(); + Transaction transaction = session.beginTransaction()) { + transaction.run(String.format( + "CREATE CONSTRAINT UNIQUE_%s_name IF NOT EXISTS ON (lock:%s) ASSERT lock.name IS UNIQUE", + collectionName, collectionName)); transaction.commit(); } } @@ -58,79 +55,93 @@ private void createLockNameUniqueConstraint() { @Override public boolean insertRecord(@NonNull LockConfiguration lockConfiguration) { // Try to insert if the record does not exists - String cypher = String.format("CREATE (lock:%s {name: $lockName, lock_until: $lockUntil, locked_at: $now, locked_by: $lockedBy })", collectionName); + String cypher = String.format( + "CREATE (lock:%s {name: $lockName, lock_until: $lockUntil, locked_at: $now, locked_by: $lockedBy })", + collectionName); Map parameters = createParameterMap(lockConfiguration); - return executeCommand(cypher, result -> { - int insertedNodes = result.consume().counters().nodesCreated(); - return insertedNodes > 0; - }, parameters, this::handleInsertionException); + return executeCommand( + cypher, + result -> { + int insertedNodes = result.consume().counters().nodesCreated(); + return insertedNodes > 0; + }, + parameters, + this::handleInsertionException); } private Map createParameterMap(@NonNull LockConfiguration lockConfiguration) { return Map.of( - "lockName", lockConfiguration.getName(), - "lockedBy", getHostname(), - "now", ClockProvider.now().toString(), - "lockUntil", lockConfiguration.getLockAtMostUntil().toString() - ); + "lockName", + lockConfiguration.getName(), + "lockedBy", + getHostname(), + "now", + ClockProvider.now().toString(), + "lockUntil", + lockConfiguration.getLockAtMostUntil().toString()); } @Override public boolean updateRecord(@NonNull LockConfiguration lockConfiguration) { - String cypher = String.format("MATCH (lock:%s) " + - "WHERE lock.name = $lockName AND lock.lock_until <= $now " + - "SET lock._LOCK_ = true " + - "WITH lock as l " + - "WHERE l.lock_until <= $now " + - "SET l.lock_until = $lockUntil, l.locked_at = $now, l.locked_by = $lockedBy " + - "REMOVE l._LOCK_ ", collectionName); + String cypher = String.format( + "MATCH (lock:%s) " + "WHERE lock.name = $lockName AND lock.lock_until <= $now " + + "SET lock._LOCK_ = true " + "WITH lock as l " + "WHERE l.lock_until <= $now " + + "SET l.lock_until = $lockUntil, l.locked_at = $now, l.locked_by = $lockedBy " + + "REMOVE l._LOCK_ ", + collectionName); Map parameters = createParameterMap(lockConfiguration); - return executeCommand(cypher, statement -> { - int updatedProperties = statement.consume().counters().propertiesSet(); - return updatedProperties > 1; //ignore explicit lock when counting the updated properties - }, parameters, this::handleUpdateException); + return executeCommand( + cypher, + statement -> { + int updatedProperties = statement.consume().counters().propertiesSet(); + return updatedProperties > 1; // ignore explicit lock when counting the updated properties + }, + parameters, + this::handleUpdateException); } @Override public boolean extend(@NonNull LockConfiguration lockConfiguration) { - String cypher = String.format("MATCH (lock:%s) " + - "WHERE lock.name = $lockName AND lock.locked_by = $lockedBy AND lock.lock_until > $now " + - "SET lock._LOCK_ = true " + - "WITH lock as l " + - "WHERE l.name = $lockName AND l.locked_by = $lockedBy AND l.lock_until > $now " + - "SET l.lock_until = $lockUntil " + - "REMOVE l._LOCK_ ", collectionName); + String cypher = String.format( + "MATCH (lock:%s) " + + "WHERE lock.name = $lockName AND lock.locked_by = $lockedBy AND lock.lock_until > $now " + + "SET lock._LOCK_ = true " + "WITH lock as l " + + "WHERE l.name = $lockName AND l.locked_by = $lockedBy AND l.lock_until > $now " + + "SET l.lock_until = $lockUntil " + "REMOVE l._LOCK_ ", + collectionName); Map parameters = createParameterMap(lockConfiguration); logger.debug("Extending lock={} until={}", lockConfiguration.getName(), lockConfiguration.getLockAtMostUntil()); - return executeCommand(cypher, statement -> { - int updatedProperties = statement.consume().counters().propertiesSet(); - return updatedProperties > 1; //ignore the explicit lock when counting the updated properties - }, parameters, this::handleUnlockException); + return executeCommand( + cypher, + statement -> { + int updatedProperties = statement.consume().counters().propertiesSet(); + return updatedProperties > 1; // ignore the explicit lock when counting the updated properties + }, + parameters, + this::handleUnlockException); } @Override public void unlock(@NonNull LockConfiguration lockConfiguration) { - String cypher = String.format("MATCH (lock:%s) WHERE lock.name = $lockName " + - "SET lock.lock_until = $lockUntil ", collectionName); + String cypher = String.format( + "MATCH (lock:%s) WHERE lock.name = $lockName " + "SET lock.lock_until = $lockUntil ", collectionName); Map parameters = Map.of( - "lockName", lockConfiguration.getName(), - "lockUntil", lockConfiguration.getUnlockTime().toString() - ); + "lockName", + lockConfiguration.getName(), + "lockUntil", + lockConfiguration.getUnlockTime().toString()); executeCommand(cypher, statement -> null, parameters, this::handleUnlockException); } private T executeCommand( - String cypher, - Function body, - Map parameters, - BiFunction exceptionHandler - ) { - try ( - Session session = getSession(); - Transaction transaction = session.beginTransaction() - ) { + String cypher, + Function body, + Map parameters, + BiFunction exceptionHandler) { + try (Session session = getSession(); + Transaction transaction = session.beginTransaction()) { Result result = transaction.run(cypher, parameters); T apply = body.apply(result); transaction.commit(); @@ -156,5 +167,4 @@ boolean handleUpdateException(String cypher, Exception e) { boolean handleUnlockException(String cypher, Exception e) { throw new LockException("Unexpected exception when unlocking", e); } - } diff --git a/providers/neo4j/shedlock-provider-neo4j/src/test/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jLockProviderIntegrationTest.java b/providers/neo4j/shedlock-provider-neo4j/src/test/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jLockProviderIntegrationTest.java index 613535309..bdbf364bf 100644 --- a/providers/neo4j/shedlock-provider-neo4j/src/test/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jLockProviderIntegrationTest.java +++ b/providers/neo4j/shedlock-provider-neo4j/src/test/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jLockProviderIntegrationTest.java @@ -1,20 +1,28 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.neo4j; +import static java.lang.Thread.sleep; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutionException; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.support.StorageBasedLockProvider; @@ -36,17 +44,6 @@ import org.testcontainers.containers.Neo4jContainer; import org.testcontainers.utility.DockerImageName; -import java.time.Duration; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import static java.lang.Thread.sleep; -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static org.assertj.core.api.Assertions.assertThat; - @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class Neo4jLockProviderIntegrationTest extends AbstractStorageBasedLockProviderIntegrationTest { protected Neo4jTestUtils testUtils; @@ -87,7 +84,9 @@ public void cleanup() { protected void assertUnlocked(String lockName) { Neo4jTestUtils.LockInfo lockInfo = getLockInfo(lockName); Instant now = ClockProvider.now(); - assertThat(lockInfo.getLockUntil()).describedAs("is unlocked").isBeforeOrEqualTo(now.truncatedTo(ChronoUnit.MILLIS).plusMillis(1)); + assertThat(lockInfo.getLockUntil()) + .describedAs("is unlocked") + .isBeforeOrEqualTo(now.truncatedTo(ChronoUnit.MILLIS).plusMillis(1)); } @Override @@ -95,16 +94,22 @@ protected void assertLocked(String lockName) { Neo4jTestUtils.LockInfo lockInfo = getLockInfo(lockName); Instant now = ClockProvider.now(); - assertThat(lockInfo.getLockUntil()).describedAs(getClass().getName() + " is locked").isAfter(now); + assertThat(lockInfo.getLockUntil()) + .describedAs(getClass().getName() + " is locked") + .isAfter(now); } @Test public void shouldCreateLockIfRecordAlreadyExists() { Map parameters = new HashMap<>(); parameters.put("name", LOCK_NAME1); - parameters.put("previousLockTime", Instant.now().minus(1, ChronoUnit.DAYS).toString()); + parameters.put( + "previousLockTime", Instant.now().minus(1, ChronoUnit.DAYS).toString()); parameters.put("lockedBy", "me"); - testUtils.executeTransactionally("CREATE (lock:shedlock { name: $name, lock_until: $previousLockTime, locked_at: $previousLockTime, locked_by: $lockedBy })", parameters, null); + testUtils.executeTransactionally( + "CREATE (lock:shedlock { name: $name, lock_until: $previousLockTime, locked_at: $previousLockTime, locked_by: $lockedBy })", + parameters, + null); assertUnlocked(LOCK_NAME1); shouldCreateLock(); } @@ -114,16 +119,13 @@ public void fuzzTestShouldWorkWithTransaction() throws ExecutionException, Inter new FuzzTester(getLockProvider()) { @Override protected Void task(int iterations, Job job) { - try ( - Session session = testUtils.getDriver().session(); - Transaction transaction = session.beginTransaction() - ) { + try (Session session = testUtils.getDriver().session(); + Transaction transaction = session.beginTransaction()) { super.task(iterations, job); transaction.commit(); return null; } catch (Throwable e) { - LoggerFactory.getLogger(getClass()) - .error("Exception caught:", e); + LoggerFactory.getLogger(getClass()).error("Exception caught:", e); return null; } } @@ -135,7 +137,6 @@ protected boolean shouldLog() { }.doFuzzTest(); } - @Test void shouldNotUpdateOnInsertIfPreviousDidNotEndWhenNotUsingDbTime() { shouldNotUpdateOnInsertIfPreviousDidNotEnd(); @@ -149,15 +150,13 @@ void shouldNotUpdateOnInsertIfPreviousDidNotEndWhenUsingDbTime() { private void shouldNotUpdateOnInsertIfPreviousDidNotEnd() { Neo4jStorageAccessor accessor = getAccessor(); - assertThat( - accessor.insertRecord(lockConfig(MY_LOCK, Duration.ofSeconds(10))) - ).isEqualTo(true); + assertThat(accessor.insertRecord(lockConfig(MY_LOCK, Duration.ofSeconds(10)))) + .isEqualTo(true); Instant originalLockValidity = testUtils.getLockedUntil(MY_LOCK); - assertThat( - accessor.insertRecord(lockConfig(MY_LOCK, Duration.ofSeconds(10))) - ).isEqualTo(false); + assertThat(accessor.insertRecord(lockConfig(MY_LOCK, Duration.ofSeconds(10)))) + .isEqualTo(false); assertThat(testUtils.getLockedUntil(MY_LOCK)).isEqualTo(originalLockValidity); } @@ -183,13 +182,14 @@ private void shouldNotUpdateOtherLockConfigurations() throws InterruptedExceptio Instant otherLockLockedUntil = testUtils.getLockedUntil(OTHER_LOCK); // wait for a while so there will be a difference in the timestamp - // when system time is used seems there is no milliseconds in the timestamp so to make a difference we have to wait for at least a second + // when system time is used seems there is no milliseconds in the timestamp so + // to make a + // difference we have to wait for at least a second sleep(1000); - // act - assertThat(accessor.updateRecord(new LockConfiguration(now(), MY_LOCK, lockAtMostFor, Duration.ZERO))).isEqualTo(true); - + assertThat(accessor.updateRecord(new LockConfiguration(now(), MY_LOCK, lockAtMostFor, Duration.ZERO))) + .isEqualTo(true); // assert assertThat(testUtils.getLockedUntil(MY_LOCK)).isAfter(myLockLockedUntil); diff --git a/providers/neo4j/shedlock-provider-neo4j/src/test/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jTestUtils.java b/providers/neo4j/shedlock-provider-neo4j/src/test/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jTestUtils.java index afc5b5f83..e911d2b3b 100644 --- a/providers/neo4j/shedlock-provider-neo4j/src/test/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jTestUtils.java +++ b/providers/neo4j/shedlock-provider-neo4j/src/test/java/net/javacrumbs/shedlock/provider/neo4j/Neo4jTestUtils.java @@ -1,31 +1,28 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.neo4j; -import org.neo4j.driver.Driver; -import org.neo4j.driver.Result; -import org.neo4j.driver.Session; -import org.neo4j.driver.Transaction; +import static java.util.Collections.singletonMap; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.function.Function; - -import static java.util.Collections.singletonMap; +import org.neo4j.driver.Driver; +import org.neo4j.driver.Result; +import org.neo4j.driver.Session; +import org.neo4j.driver.Transaction; public final class Neo4jTestUtils { @@ -39,7 +36,8 @@ public void executeTransactionally(String query) { executeTransactionally(query, new HashMap<>(), null); } - public T executeTransactionally(String query, Map parameters, Function resultTransformer) { + public T executeTransactionally( + String query, Map parameters, Function resultTransformer) { T transformedResult = null; try (Session session = driver.session()) { Transaction transaction = session.beginTransaction(); @@ -54,24 +52,26 @@ public T executeTransactionally(String query, Map parameters public Instant getLockedUntil(String lockName) { Map parameters = singletonMap("lockName", lockName); - return executeTransactionally("MATCH (lock:shedlock) WHERE lock.name = $lockName return lock.lock_until", - parameters, result -> result.stream() - .findFirst() - .map(it -> Instant.parse(it.get("lock.lock_until").asString())) - .orElse(null)); + return executeTransactionally( + "MATCH (lock:shedlock) WHERE lock.name = $lockName return lock.lock_until", + parameters, + result -> result.stream() + .findFirst() + .map(it -> Instant.parse(it.get("lock.lock_until").asString())) + .orElse(null)); } public LockInfo getLockInfo(String lockName) { Map parameters = singletonMap("lockName", lockName); - return executeTransactionally("MATCH (lock:shedlock) WHERE lock.name = $lockName RETURN lock.name, lock.lock_until, localdatetime() as db_time ", parameters, result -> - result.stream() - .findFirst() - .map(it -> new LockInfo( - it.get("lock.name").asString(), - Instant.parse(it.get("lock.lock_until").asString()) - ) - ) - ).orElse(null); + return executeTransactionally( + "MATCH (lock:shedlock) WHERE lock.name = $lockName RETURN lock.name, lock.lock_until, localdatetime() as db_time ", + parameters, + result -> result.stream() + .findFirst() + .map(it -> new LockInfo( + it.get("lock.name").asString(), + Instant.parse(it.get("lock.lock_until").asString())))) + .orElse(null); } public void clean() { diff --git a/providers/opensearch/shedlock-provider-opensearch/src/main/java/net/javacrumbs/shedlock/provider/opensearch/OpenSearchLockProvider.java b/providers/opensearch/shedlock-provider-opensearch/src/main/java/net/javacrumbs/shedlock/provider/opensearch/OpenSearchLockProvider.java index 6746ec2db..e0e61d260 100644 --- a/providers/opensearch/shedlock-provider-opensearch/src/main/java/net/javacrumbs/shedlock/provider/opensearch/OpenSearchLockProvider.java +++ b/providers/opensearch/shedlock-provider-opensearch/src/main/java/net/javacrumbs/shedlock/provider/opensearch/OpenSearchLockProvider.java @@ -1,20 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.opensearch; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static net.javacrumbs.shedlock.support.Utils.getHostname; +import static org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE; + +import java.io.IOException; +import java.time.Instant; +import java.util.Collections; +import java.util.Map; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; @@ -31,21 +38,13 @@ import org.opensearch.script.Script; import org.opensearch.script.ScriptType; -import java.io.IOException; -import java.time.Instant; -import java.util.Collections; -import java.util.Map; -import java.util.Optional; - -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static net.javacrumbs.shedlock.support.Utils.getHostname; -import static org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE; - /** - * Lock using OpenSearch >= . - * Requires opensearch-rest-high-level-client > 1.1.0 + * Lock using OpenSearch >= . Requires opensearch-rest-high-level-client > + * 1.1.0 + * *

* It uses a collection that contains documents like this: + * *

  * {
  *    "name" : "lock name",
@@ -60,23 +59,20 @@
  *    "lockedBy" : "hostname"
  * }
  * 
+ * *

- * lockedAt and lockedBy are just for troubleshooting and are not read by the code + * lockedAt and lockedBy are just for troubleshooting and are not read by the + * code * *

    - *
  1. - * Attempts to insert a new lock record. As an optimization, we keep in-memory track of created lock records. If the record - * has been inserted, returns lock. - *
  2. - *
  3. - * We will try to update lock record using filter _id == name AND lock_until <= now - *
  4. - *
  5. - * If the update succeeded (1 updated document), we have the lock. If the update failed (0 updated documents) somebody else holds the lock - *
  6. - *
  7. - * When unlocking, lock_until is set to now. - *
  8. + *
  9. Attempts to insert a new lock record. As an optimization, we keep + * in-memory track of created lock records. If the record has been inserted, + * returns lock. + *
  10. We will try to update lock record using filter _id == name AND lock_until + * <= now + *
  11. If the update succeeded (1 updated document), we have the lock. If the + * update failed (0 updated documents) somebody else holds the lock + *
  12. When unlocking, lock_until is set to now. *
*/ public class OpenSearchLockProvider implements LockProvider { @@ -86,15 +82,10 @@ public class OpenSearchLockProvider implements LockProvider { static final String LOCKED_BY = "lockedBy"; static final String NAME = "name"; - - private static final String UPDATE_SCRIPT = - "if (ctx._source." + LOCK_UNTIL + " <= " + "params." + LOCKED_AT + ") { " + - "ctx._source." + LOCKED_BY + " = params." + LOCKED_BY + "; " + - "ctx._source." + LOCKED_AT + " = params." + LOCKED_AT + "; " + - "ctx._source." + LOCK_UNTIL + " = params." + LOCK_UNTIL + "; " + - "} else { " + - "ctx.op = 'none' " + - "}"; + private static final String UPDATE_SCRIPT = "if (ctx._source." + LOCK_UNTIL + " <= " + "params." + LOCKED_AT + + ") { " + "ctx._source." + LOCKED_BY + " = params." + LOCKED_BY + "; " + "ctx._source." + LOCKED_AT + + " = params." + LOCKED_AT + "; " + "ctx._source." + LOCK_UNTIL + " = params." + LOCK_UNTIL + "; " + + "} else { " + "ctx.op = 'none' " + "}"; private final RestHighLevelClient highLevelClient; private final String hostname; @@ -114,16 +105,11 @@ public OpenSearchLockProvider(@NonNull RestHighLevelClient highLevelClient) { @NonNull public Optional lock(@NonNull LockConfiguration lockConfiguration) { try { - Map lockObject = lockObject(lockConfiguration.getName(), - lockConfiguration.getLockAtMostUntil(), - now()); + Map lockObject = + lockObject(lockConfiguration.getName(), lockConfiguration.getLockAtMostUntil(), now()); UpdateRequest ur = updateRequest(lockConfiguration) - .script(new Script(ScriptType.INLINE, - "painless", - UPDATE_SCRIPT, - lockObject) - ) - .upsert(lockObject); + .script(new Script(ScriptType.INLINE, "painless", UPDATE_SCRIPT, lockObject)) + .upsert(lockObject); UpdateResponse res = highLevelClient.update(ur, RequestOptions.DEFAULT); if (res.getResult() != DocWriteResponse.Result.NOOP) { return Optional.of(new OpenSearchSimpleLock(lockConfiguration)); @@ -140,19 +126,19 @@ public Optional lock(@NonNull LockConfiguration lockConfiguration) { } private UpdateRequest updateRequest(@NonNull LockConfiguration lockConfiguration) { - return new UpdateRequest() - .index(index) - .id(lockConfiguration.getName()) - .setRefreshPolicy(IMMEDIATE); + return new UpdateRequest().index(index).id(lockConfiguration.getName()).setRefreshPolicy(IMMEDIATE); } private Map lockObject(String name, Instant lockUntil, Instant lockedAt) { return Map.of( - NAME, name, - LOCKED_BY, hostname, - LOCKED_AT, lockedAt.toEpochMilli(), - LOCK_UNTIL, lockUntil.toEpochMilli() - ); + NAME, + name, + LOCKED_BY, + hostname, + LOCKED_AT, + lockedAt.toEpochMilli(), + LOCK_UNTIL, + lockUntil.toEpochMilli()); } private final class OpenSearchSimpleLock extends AbstractSimpleLock { @@ -166,10 +152,13 @@ public void doUnlock() { // Set lockUtil to now or lockAtLeastUntil whichever is later try { UpdateRequest ur = updateRequest(lockConfiguration) - .script(new Script(ScriptType.INLINE, - "painless", - "ctx._source.lockUntil = params.unlockTime", - Collections.singletonMap("unlockTime", lockConfiguration.getUnlockTime().toEpochMilli()))); + .script(new Script( + ScriptType.INLINE, + "painless", + "ctx._source.lockUntil = params.unlockTime", + Collections.singletonMap( + "unlockTime", + lockConfiguration.getUnlockTime().toEpochMilli()))); highLevelClient.update(ur, RequestOptions.DEFAULT); } catch (IOException | OpenSearchException e) { throw new LockException("Unexpected exception occurred", e); diff --git a/providers/opensearch/shedlock-provider-opensearch/src/test/java/net/javacrumbs/container/OpenSearchContainer.java b/providers/opensearch/shedlock-provider-opensearch/src/test/java/net/javacrumbs/container/OpenSearchContainer.java index 1c43d0d41..a5ff4309a 100644 --- a/providers/opensearch/shedlock-provider-opensearch/src/test/java/net/javacrumbs/container/OpenSearchContainer.java +++ b/providers/opensearch/shedlock-provider-opensearch/src/test/java/net/javacrumbs/container/OpenSearchContainer.java @@ -1,26 +1,25 @@ package net.javacrumbs.container; +import static java.net.HttpURLConnection.HTTP_OK; +import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; + +import java.time.Duration; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.wait.strategy.HttpWaitStrategy; import org.testcontainers.images.builder.ImageFromDockerfile; import org.testcontainers.utility.Base58; -import java.time.Duration; - -import static java.net.HttpURLConnection.HTTP_OK; -import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; - public class OpenSearchContainer extends GenericContainer { static final int OPENSEARCH_DEFAULT_PORT = 9200; static final int OPENSEARCH_DEFAULT_TCP_PORT = 9300; + public OpenSearchContainer(String dockerImageName) { super(dockerImageName); } private ImageFromDockerfile prepareImage(String imageName) { - return new ImageFromDockerfile() - .withDockerfileFromBuilder(builder -> builder.from(imageName)); + return new ImageFromDockerfile().withDockerfileFromBuilder(builder -> builder.from(imageName)); } @Override @@ -29,9 +28,9 @@ protected void configure() { withEnv("discovery.type", "single-node"); addExposedPorts(OPENSEARCH_DEFAULT_PORT, OPENSEARCH_DEFAULT_TCP_PORT); setWaitStrategy(new HttpWaitStrategy() - .forPort(OPENSEARCH_DEFAULT_PORT) - .forStatusCodeMatching(response -> response == HTTP_OK || response == HTTP_UNAUTHORIZED) - .withStartupTimeout(Duration.ofMinutes(2))); + .forPort(OPENSEARCH_DEFAULT_PORT) + .forStatusCodeMatching(response -> response == HTTP_OK || response == HTTP_UNAUTHORIZED) + .withStartupTimeout(Duration.ofMinutes(2))); setImage(prepareImage(getDockerImageName())); } diff --git a/providers/opensearch/shedlock-provider-opensearch/src/test/java/net/javacrumbs/shedlock/provider/opensearch/OpenSearchLockProviderTest.java b/providers/opensearch/shedlock-provider-opensearch/src/test/java/net/javacrumbs/shedlock/provider/opensearch/OpenSearchLockProviderTest.java index 0893f6d99..8505d4f67 100644 --- a/providers/opensearch/shedlock-provider-opensearch/src/test/java/net/javacrumbs/shedlock/provider/opensearch/OpenSearchLockProviderTest.java +++ b/providers/opensearch/shedlock-provider-opensearch/src/test/java/net/javacrumbs/shedlock/provider/opensearch/OpenSearchLockProviderTest.java @@ -1,20 +1,30 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.opensearch; +import static net.javacrumbs.shedlock.provider.opensearch.OpenSearchLockProvider.LOCKED_AT; +import static net.javacrumbs.shedlock.provider.opensearch.OpenSearchLockProvider.LOCKED_BY; +import static net.javacrumbs.shedlock.provider.opensearch.OpenSearchLockProvider.LOCK_UNTIL; +import static net.javacrumbs.shedlock.provider.opensearch.OpenSearchLockProvider.NAME; +import static net.javacrumbs.shedlock.provider.opensearch.OpenSearchLockProvider.SCHEDLOCK_DEFAULT_INDEX; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +import java.io.IOException; +import java.time.Duration; +import java.util.Date; +import java.util.Map; import net.javacrumbs.container.OpenSearchContainer; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.test.support.AbstractLockProviderIntegrationTest; @@ -29,35 +39,21 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import java.io.IOException; -import java.time.Duration; -import java.util.Date; -import java.util.Map; - -import static net.javacrumbs.shedlock.provider.opensearch.OpenSearchLockProvider.LOCKED_AT; -import static net.javacrumbs.shedlock.provider.opensearch.OpenSearchLockProvider.LOCKED_BY; -import static net.javacrumbs.shedlock.provider.opensearch.OpenSearchLockProvider.LOCK_UNTIL; -import static net.javacrumbs.shedlock.provider.opensearch.OpenSearchLockProvider.NAME; -import static net.javacrumbs.shedlock.provider.opensearch.OpenSearchLockProvider.SCHEDLOCK_DEFAULT_INDEX; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; - @Testcontainers public class OpenSearchLockProviderTest extends AbstractLockProviderIntegrationTest { @Container private static final OpenSearchContainer container = new OpenSearchContainer("opensearchproject/opensearch:1.1.0") - .withStartupTimeout(Duration.ofMinutes(2)) - .withEnv("plugins.security.disabled", "true") - .withStartupAttempts(2); + .withStartupTimeout(Duration.ofMinutes(2)) + .withEnv("plugins.security.disabled", "true") + .withStartupAttempts(2); + private RestHighLevelClient highLevelClient; private OpenSearchLockProvider lockProvider; @BeforeEach public void setUp() { - highLevelClient = new RestHighLevelClient( - RestClient.builder(HttpHost.create(container.getHttpHostAddress())) - ); + highLevelClient = new RestHighLevelClient(RestClient.builder(HttpHost.create(container.getHttpHostAddress()))); lockProvider = new OpenSearchLockProvider(highLevelClient); } diff --git a/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/AbstractR2dbcStorageAccessor.java b/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/AbstractR2dbcStorageAccessor.java index 1f9de49ef..833fd3647 100644 --- a/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/AbstractR2dbcStorageAccessor.java +++ b/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/AbstractR2dbcStorageAccessor.java @@ -15,8 +15,13 @@ */ package net.javacrumbs.shedlock.provider.r2dbc; +import static java.util.Objects.requireNonNull; + import io.r2dbc.spi.R2dbcDataIntegrityViolationException; import io.r2dbc.spi.Statement; +import java.time.Instant; +import java.util.function.BiFunction; +import java.util.function.Function; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.support.AbstractStorageAccessor; @@ -25,15 +30,7 @@ import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; -import java.time.Instant; -import java.util.function.BiFunction; -import java.util.function.Function; - -import static java.util.Objects.requireNonNull; - -/** - * Internal class, please do not use. - */ +/** Internal class, please do not use. */ abstract class AbstractR2dbcStorageAccessor extends AbstractStorageAccessor { private final String tableName; @@ -43,12 +40,14 @@ public AbstractR2dbcStorageAccessor(@NonNull String tableName) { @Override public boolean insertRecord(@NonNull LockConfiguration lockConfiguration) { - return Boolean.TRUE.equals(Mono.from(insertRecordReactive(lockConfiguration)).block()); + return Boolean.TRUE.equals( + Mono.from(insertRecordReactive(lockConfiguration)).block()); } @Override public boolean updateRecord(@NonNull LockConfiguration lockConfiguration) { - return Boolean.TRUE.equals(Mono.from(updateRecordReactive(lockConfiguration)).block()); + return Boolean.TRUE.equals( + Mono.from(updateRecordReactive(lockConfiguration)).block()); } @Override @@ -62,58 +61,84 @@ public void unlock(@NonNull LockConfiguration lockConfiguration) { } public Publisher insertRecordReactive(@NonNull LockConfiguration lockConfiguration) { - // Try to insert if the record does not exist (not optimal, but the simplest platform agnostic way) - String sql = "INSERT INTO " + tableName + "(name, lock_until, locked_at, locked_by) VALUES(" + toParameter(1, "name") + ", " + toParameter(2, "lock_until") + ", " + toParameter(3, "locked_at") + ", " + toParameter(4, "locked_by") + ")"; - return executeCommand(sql, statement -> { - bind(statement, 0, "name", lockConfiguration.getName()); - bind(statement, 1, "lock_until", lockConfiguration.getLockAtMostUntil()); - bind(statement, 2, "locked_at", ClockProvider.now()); - bind(statement, 3, "locked_by", getHostname()); - return Mono.from(statement.execute()).flatMap(it -> Mono.from(it.getRowsUpdated())).map(it -> it > 0); - }, this::handleInsertionException); + // Try to insert if the record does not exist (not optimal, but the simplest + // platform agnostic + // way) + String sql = "INSERT INTO " + tableName + "(name, lock_until, locked_at, locked_by) VALUES(" + + toParameter(1, "name") + ", " + toParameter(2, "lock_until") + ", " + toParameter(3, "locked_at") + + ", " + toParameter(4, "locked_by") + ")"; + return executeCommand( + sql, + statement -> { + bind(statement, 0, "name", lockConfiguration.getName()); + bind(statement, 1, "lock_until", lockConfiguration.getLockAtMostUntil()); + bind(statement, 2, "locked_at", ClockProvider.now()); + bind(statement, 3, "locked_by", getHostname()); + return Mono.from(statement.execute()) + .flatMap(it -> Mono.from(it.getRowsUpdated())) + .map(it -> it > 0); + }, + this::handleInsertionException); } public Publisher updateRecordReactive(@NonNull LockConfiguration lockConfiguration) { - String sql = "UPDATE " + tableName + " SET lock_until = " + toParameter(1, "lock_until") + ", locked_at = " + toParameter(2, "locked_at") + ", locked_by = " + toParameter(3, "locked_by") + " WHERE name = " + toParameter(4, "name") + " AND lock_until <= " + toParameter(5, "now"); - return executeCommand(sql, statement -> { - Instant now = ClockProvider.now(); - bind(statement, 0, "lock_until", lockConfiguration.getLockAtMostUntil()); - bind(statement, 1, "locked_at", now); - bind(statement, 2, "locked_by", getHostname()); - bind(statement, 3, "name", lockConfiguration.getName()); - bind(statement, 4, "now", now); - return Mono.from(statement.execute()).flatMap(it -> Mono.from(it.getRowsUpdated())).map(it -> it > 0); - }, this::handleUpdateException); + String sql = "UPDATE " + tableName + " SET lock_until = " + toParameter(1, "lock_until") + ", locked_at = " + + toParameter(2, "locked_at") + ", locked_by = " + toParameter(3, "locked_by") + " WHERE name = " + + toParameter(4, "name") + " AND lock_until <= " + toParameter(5, "now"); + return executeCommand( + sql, + statement -> { + Instant now = ClockProvider.now(); + bind(statement, 0, "lock_until", lockConfiguration.getLockAtMostUntil()); + bind(statement, 1, "locked_at", now); + bind(statement, 2, "locked_by", getHostname()); + bind(statement, 3, "name", lockConfiguration.getName()); + bind(statement, 4, "now", now); + return Mono.from(statement.execute()) + .flatMap(it -> Mono.from(it.getRowsUpdated())) + .map(it -> it > 0); + }, + this::handleUpdateException); } public Publisher extendReactive(@NonNull LockConfiguration lockConfiguration) { - String sql = "UPDATE " + tableName + " SET lock_until = " + toParameter(1, "lock_until") + " WHERE name = " + toParameter(2, "name") + " AND locked_by = " + toParameter(3, "locked_by") + " AND lock_until > " + toParameter(4, "now"); + String sql = "UPDATE " + tableName + " SET lock_until = " + toParameter(1, "lock_until") + " WHERE name = " + + toParameter(2, "name") + " AND locked_by = " + toParameter(3, "locked_by") + " AND lock_until > " + + toParameter(4, "now"); logger.debug("Extending lock={} until={}", lockConfiguration.getName(), lockConfiguration.getLockAtMostUntil()); - return executeCommand(sql, statement -> { - bind(statement, 0, "lock_until", lockConfiguration.getLockAtMostUntil()); - bind(statement, 1, "name", lockConfiguration.getName()); - bind(statement, 2, "locked_by", getHostname()); - bind(statement, 3, "now", ClockProvider.now()); - return Mono.from(statement.execute()).flatMap(it -> Mono.from(it.getRowsUpdated())).map(it -> it > 0); - }, this::handleUnlockException); + return executeCommand( + sql, + statement -> { + bind(statement, 0, "lock_until", lockConfiguration.getLockAtMostUntil()); + bind(statement, 1, "name", lockConfiguration.getName()); + bind(statement, 2, "locked_by", getHostname()); + bind(statement, 3, "now", ClockProvider.now()); + return Mono.from(statement.execute()) + .flatMap(it -> Mono.from(it.getRowsUpdated())) + .map(it -> it > 0); + }, + this::handleUnlockException); } public Publisher unlockReactive(@NonNull LockConfiguration lockConfiguration) { - String sql = "UPDATE " + tableName + " SET lock_until = " + toParameter(1, "lock_until") + " WHERE name = " + toParameter(2, "name"); - return executeCommand(sql, statement -> { - bind(statement, 0, "lock_until", lockConfiguration.getUnlockTime()); - bind(statement, 1, "name", lockConfiguration.getName()); - return Mono.from(statement.execute()).flatMap(it -> Mono.from(it.getRowsUpdated())).then(); - }, (s, t) -> handleUnlockException(s, t).then()); + String sql = "UPDATE " + tableName + " SET lock_until = " + toParameter(1, "lock_until") + " WHERE name = " + + toParameter(2, "name"); + return executeCommand( + sql, + statement -> { + bind(statement, 0, "lock_until", lockConfiguration.getUnlockTime()); + bind(statement, 1, "name", lockConfiguration.getName()); + return Mono.from(statement.execute()) + .flatMap(it -> Mono.from(it.getRowsUpdated())) + .then(); + }, + (s, t) -> handleUnlockException(s, t).then()); } protected abstract Mono executeCommand( - String sql, - Function> body, - BiFunction> exceptionHandler - ); + String sql, Function> body, BiFunction> exceptionHandler); protected abstract String toParameter(int index, String name); @@ -123,8 +148,11 @@ Mono handleInsertionException(String sql, Throwable e) { if (e instanceof R2dbcDataIntegrityViolationException) { // lock record already exists } else { - // can not throw exception here, some drivers (Postgres) do not throw SQLIntegrityConstraintViolationException on duplicate key - // we will try update in the next step, su if there is another problem, an exception will be thrown there + // can not throw exception here, some drivers (Postgres) do not throw + // SQLIntegrityConstraintViolationException on duplicate key + // we will try update in the next step, su if there is another problem, an + // exception will be + // thrown there logger.debug("Exception thrown when inserting record", e); } return Mono.just(false); diff --git a/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/R2dbcAdapter.java b/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/R2dbcAdapter.java index 55ec00475..427ed8197 100644 --- a/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/R2dbcAdapter.java +++ b/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/R2dbcAdapter.java @@ -1,12 +1,11 @@ package net.javacrumbs.shedlock.provider.r2dbc; import io.r2dbc.spi.Statement; -import net.javacrumbs.shedlock.support.annotation.NonNull; - import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.function.Function; +import net.javacrumbs.shedlock.support.annotation.NonNull; abstract class R2dbcAdapter { private static final String MSSQL_NAME = "Microsoft SQL Server"; @@ -18,25 +17,13 @@ abstract class R2dbcAdapter { static R2dbcAdapter create(@NonNull String driver) { return switch (driver) { case MSSQL_NAME -> new DefaultR2dbcAdapter( - (index, name) -> "@" + name, - R2dbcAdapter::toLocalDate, - R2dbcAdapter::bindByName - ); + (index, name) -> "@" + name, R2dbcAdapter::toLocalDate, R2dbcAdapter::bindByName); case MYSQL_NAME, JASYNC_MYSQL_NAME, MARIA_NAME -> new DefaultR2dbcAdapter( - (index, name) -> "?", - R2dbcAdapter::toLocalDate, - R2dbcAdapter::bindByIndex - ); + (index, name) -> "?", R2dbcAdapter::toLocalDate, R2dbcAdapter::bindByIndex); case ORACLE_NAME -> new DefaultR2dbcAdapter( - (index, name) -> ":" + name, - R2dbcAdapter::toLocalDate, - R2dbcAdapter::bindByName - ); + (index, name) -> ":" + name, R2dbcAdapter::toLocalDate, R2dbcAdapter::bindByName); default -> new DefaultR2dbcAdapter( - (index, name) -> "$" + index, - R2dbcAdapter::toInstant, - R2dbcAdapter::bindByIndex - ); + (index, name) -> "$" + index, R2dbcAdapter::toInstant, R2dbcAdapter::bindByIndex); }; } @@ -51,11 +38,11 @@ private static LocalDateTime toLocalDate(Instant date) { private static void bindByName(Statement statement, int index, String name, Object value) { statement.bind(name, value); } + private static void bindByIndex(Statement statement, int index, String name, Object value) { statement.bind(index, value); } - protected abstract String toParameter(int index, String name); public abstract void bind(Statement statement, int index, String name, Object value); @@ -66,10 +53,9 @@ private static class DefaultR2dbcAdapter extends R2dbcAdapter { private final ValueBinder binder; private DefaultR2dbcAdapter( - @NonNull ParameterResolver parameterResolver, - @NonNull Function dateConverter, - @NonNull ValueBinder binder - ) { + @NonNull ParameterResolver parameterResolver, + @NonNull Function dateConverter, + @NonNull ValueBinder binder) { this.parameterResolver = parameterResolver; this.dateConverter = dateConverter; this.binder = binder; diff --git a/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/R2dbcLockProvider.java b/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/R2dbcLockProvider.java index f0cf43917..efa891a8e 100644 --- a/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/R2dbcLockProvider.java +++ b/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/R2dbcLockProvider.java @@ -20,25 +20,20 @@ import net.javacrumbs.shedlock.support.annotation.NonNull; /** - * Lock provided by plain R2DBC SPI. It uses a table that contains lock_name and locked_until. + * Lock provided by plain R2DBC SPI. It uses a table that contains lock_name and + * locked_until. + * *

    - *
  1. - * Attempts to insert a new lock record. Since lock name is a primary key, it fails if the record already exists. As an optimization, - * we keep in-memory track of created lock records. - *
  2. - *
  3. - * If the insert succeeds (1 inserted row) we have the lock. - *
  4. - *
  5. - * If the insert failed due to duplicate key or we have skipped the insertion, we will try to update lock record using - * UPDATE tableName SET lock_until = :lockUntil WHERE name = :lockName AND lock_until <= :now - *
  6. - *
  7. - * If the update succeeded (1 updated row), we have the lock. If the update failed (0 updated rows) somebody else holds the lock - *
  8. - *
  9. - * When unlocking, lock_until is set to now. - *
  10. + *
  11. Attempts to insert a new lock record. Since lock name is a primary key, + * it fails if the record already exists. As an optimization, we keep in-memory + * track of created lock records. + *
  12. If the insert succeeds (1 inserted row) we have the lock. + *
  13. If the insert failed due to duplicate key or we have skipped the + * insertion, we will try to update lock record using UPDATE tableName SET + * lock_until = :lockUntil WHERE name = :lockName AND lock_until <= :now + *
  14. If the update succeeded (1 updated row), we have the lock. If the update + * failed (0 updated rows) somebody else holds the lock + *
  15. When unlocking, lock_until is set to now. *
*/ public class R2dbcLockProvider extends StorageBasedLockProvider { diff --git a/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/R2dbcStorageAccessor.java b/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/R2dbcStorageAccessor.java index 5d392d2ec..2941ed928 100644 --- a/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/R2dbcStorageAccessor.java +++ b/providers/r2dbc/shedlock-provider-r2dbc/src/main/java/net/javacrumbs/shedlock/provider/r2dbc/R2dbcStorageAccessor.java @@ -15,16 +15,15 @@ */ package net.javacrumbs.shedlock.provider.r2dbc; +import static java.util.Objects.requireNonNull; + import io.r2dbc.spi.Connection; import io.r2dbc.spi.ConnectionFactory; import io.r2dbc.spi.Statement; -import net.javacrumbs.shedlock.support.annotation.NonNull; -import reactor.core.publisher.Mono; - import java.util.function.BiFunction; import java.util.function.Function; - -import static java.util.Objects.requireNonNull; +import net.javacrumbs.shedlock.support.annotation.NonNull; +import reactor.core.publisher.Mono; class R2dbcStorageAccessor extends AbstractR2dbcStorageAccessor { @@ -38,22 +37,19 @@ class R2dbcStorageAccessor extends AbstractR2dbcStorageAccessor { @Override protected Mono executeCommand( - String sql, - Function> body, - BiFunction> exceptionHandler - ) { + String sql, Function> body, BiFunction> exceptionHandler) { return Mono.usingWhen( - Mono.from(connectionFactory.create()).doOnNext(it -> it.setAutoCommit(true)), - conn -> body.apply(conn.createStatement(sql)).onErrorResume(throwable -> exceptionHandler.apply(sql, throwable)), - Connection::close, - (connection, throwable) -> Mono.from(connection.close()).then(exceptionHandler.apply(sql, throwable)), - connection -> Mono.from(connection.close()).then() - ); + Mono.from(connectionFactory.create()).doOnNext(it -> it.setAutoCommit(true)), + conn -> body.apply(conn.createStatement(sql)) + .onErrorResume(throwable -> exceptionHandler.apply(sql, throwable)), + Connection::close, + (connection, throwable) -> Mono.from(connection.close()).then(exceptionHandler.apply(sql, throwable)), + connection -> Mono.from(connection.close()).then()); } @Override protected String toParameter(int index, String name) { - return getAdapter().toParameter(index, name); + return getAdapter().toParameter(index, name); } @Override diff --git a/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/AbstractR2dbcTest.java b/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/AbstractR2dbcTest.java index e283e3626..b325e92e4 100644 --- a/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/AbstractR2dbcTest.java +++ b/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/AbstractR2dbcTest.java @@ -1,10 +1,14 @@ package net.javacrumbs.shedlock.provider.r2dbc; +import static io.r2dbc.spi.ConnectionFactoryOptions.PASSWORD; +import static io.r2dbc.spi.ConnectionFactoryOptions.USER; + import io.r2dbc.pool.ConnectionPool; import io.r2dbc.pool.ConnectionPoolConfiguration; import io.r2dbc.spi.ConnectionFactories; import io.r2dbc.spi.ConnectionFactory; import io.r2dbc.spi.ConnectionFactoryOptions; +import java.time.Duration; import net.javacrumbs.shedlock.support.StorageBasedLockProvider; import net.javacrumbs.shedlock.test.support.jdbc.AbstractJdbcLockProviderIntegrationTest; import net.javacrumbs.shedlock.test.support.jdbc.DbConfig; @@ -12,11 +16,6 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.TestInstance; -import java.time.Duration; - -import static io.r2dbc.spi.ConnectionFactoryOptions.PASSWORD; -import static io.r2dbc.spi.ConnectionFactoryOptions.USER; - @TestInstance(TestInstance.Lifecycle.PER_CLASS) abstract class AbstractR2dbcTest extends AbstractJdbcLockProviderIntegrationTest { private final DbConfig dbConfig; @@ -32,18 +31,16 @@ public void startDb() { getDbConfig().startDb(); ConnectionFactory cf = ConnectionFactories.get( - ConnectionFactoryOptions - .parse(getDbConfig().getR2dbcUrl()) - .mutate() - .option(USER, getDbConfig().getUsername()) - .option(PASSWORD, getDbConfig().getPassword()) - .build() - ); + ConnectionFactoryOptions.parse(getDbConfig().getR2dbcUrl()) + .mutate() + .option(USER, getDbConfig().getUsername()) + .option(PASSWORD, getDbConfig().getPassword()) + .build()); ConnectionPoolConfiguration configuration = ConnectionPoolConfiguration.builder(cf) - .maxIdleTime(Duration.ofMillis(1000)) - .maxSize(20) - .build(); + .maxIdleTime(Duration.ofMillis(1000)) + .maxSize(20) + .build(); connectionFactory = new ConnectionPool(configuration); } diff --git a/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/MariaR2dbcLockProviderIntegrationTest.java b/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/MariaR2dbcLockProviderIntegrationTest.java index c21d4285b..559258d76 100644 --- a/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/MariaR2dbcLockProviderIntegrationTest.java +++ b/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/MariaR2dbcLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.r2dbc; diff --git a/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/MsSqlR2dbcLockProviderIntegrationTest.java b/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/MsSqlR2dbcLockProviderIntegrationTest.java index c14201ad8..6f7b845a3 100644 --- a/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/MsSqlR2dbcLockProviderIntegrationTest.java +++ b/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/MsSqlR2dbcLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.r2dbc; diff --git a/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/MySqlR2dbcLockProviderIntegrationTest.java b/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/MySqlR2dbcLockProviderIntegrationTest.java index ab0a6e0f2..b073b22e1 100644 --- a/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/MySqlR2dbcLockProviderIntegrationTest.java +++ b/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/MySqlR2dbcLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.r2dbc; diff --git a/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/OracleR2dbcLockProviderIntegrationTest.java b/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/OracleR2dbcLockProviderIntegrationTest.java index e1a2b751c..10e0cccb1 100644 --- a/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/OracleR2dbcLockProviderIntegrationTest.java +++ b/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/OracleR2dbcLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.r2dbc; diff --git a/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/PostgresR2dbcLockProviderIntegrationTest.java b/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/PostgresR2dbcLockProviderIntegrationTest.java index d994cb961..a3901977a 100644 --- a/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/PostgresR2dbcLockProviderIntegrationTest.java +++ b/providers/r2dbc/shedlock-provider-r2dbc/src/test/java/net/javacrumbs/shedlock/provider/r2dbc/PostgresR2dbcLockProviderIntegrationTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.r2dbc; diff --git a/providers/redis/shedlock-provider-redis-jedis4/src/main/java/net/javacrumbs/shedlock/provider/redis/jedis4/JedisLockProvider.java b/providers/redis/shedlock-provider-redis-jedis4/src/main/java/net/javacrumbs/shedlock/provider/redis/jedis4/JedisLockProvider.java index 7b9f8a34b..ea1224c67 100644 --- a/providers/redis/shedlock-provider-redis-jedis4/src/main/java/net/javacrumbs/shedlock/provider/redis/jedis4/JedisLockProvider.java +++ b/providers/redis/shedlock-provider-redis-jedis4/src/main/java/net/javacrumbs/shedlock/provider/redis/jedis4/JedisLockProvider.java @@ -1,20 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.redis.jedis4; +import static net.javacrumbs.shedlock.support.Utils.getHostname; +import static net.javacrumbs.shedlock.support.Utils.toIsoString; +import static redis.clients.jedis.params.SetParams.setParams; + +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.ExtensibleLockProvider; @@ -27,16 +32,10 @@ import redis.clients.jedis.params.SetParams; import redis.clients.jedis.util.Pool; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; - -import static net.javacrumbs.shedlock.support.Utils.getHostname; -import static net.javacrumbs.shedlock.support.Utils.toIsoString; -import static redis.clients.jedis.params.SetParams.setParams; - /** - * Uses Redis's `SET resource-name anystring NX PX max-lock-ms-time` as locking mechanism. + * Uses Redis's `SET resource-name anystring NX PX max-lock-ms-time` as locking + * mechanism. + * *

* See Set command */ @@ -55,9 +54,12 @@ public JedisLockProvider(@NonNull Pool jedisPool) { /** * Creates JedisLockProvider * - * @param jedisPool Jedis connection pool - * @param environment environment is part of the key and thus makes sure there is not key conflict between - * multiple ShedLock instances running on the same Redis + * @param jedisPool + * Jedis connection pool + * @param environment + * environment is part of the key and thus makes sure there is not + * key conflict between multiple ShedLock instances running on the + * same Redis */ public JedisLockProvider(@NonNull Pool jedisPool, @NonNull String environment) { this.jedisTemplate = new JedisPoolTemplate(jedisPool); @@ -67,9 +69,12 @@ public JedisLockProvider(@NonNull Pool jedisPool, @NonNull String environ /** * Creates JedisLockProvider * - * @param jedisCommands implementation of JedisCommands. - * @param environment environment is part of the key and thus makes sure there is not key conflict between - * multiple ShedLock instances running on the same Redis + * @param jedisCommands + * implementation of JedisCommands. + * @param environment + * environment is part of the key and thus makes sure there is not + * key conflict between multiple ShedLock instances running on the + * same Redis */ public JedisLockProvider(@NonNull JedisCommands jedisCommands, @NonNull String environment) { this.jedisTemplate = new JedisCommandsTemplate(jedisCommands); @@ -106,7 +111,6 @@ private Optional extend(LockConfiguration lockConfiguration) { return Optional.empty(); } - private String extendKeyExpiration(String key, long expiration) { return jedisTemplate.set(key, buildValue(), setParams().xx().px(expiration)); } @@ -115,7 +119,6 @@ private void deleteKey(String key) { jedisTemplate.del(key); } - private static final class RedisLock extends AbstractSimpleLock { private final String key; private final JedisLockProvider jedisLockProvider; @@ -170,30 +173,30 @@ private interface JedisTemplate { private record JedisPoolTemplate(Pool jedisPool) implements JedisTemplate { @Override - public String set(String key, String value, SetParams setParams) { - try (Jedis jedis = jedisPool.getResource()) { - return jedis.set(key, value, setParams); - } + public String set(String key, String value, SetParams setParams) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.set(key, value, setParams); } + } - @Override - public void del(String key) { - try (Jedis jedis = jedisPool.getResource()) { - jedis.del(key); - } + @Override + public void del(String key) { + try (Jedis jedis = jedisPool.getResource()) { + jedis.del(key); } } + } private record JedisCommandsTemplate(JedisCommands jedisCommands) implements JedisTemplate { @Override - public String set(String key, String value, SetParams setParams) { - return jedisCommands.set(key, value, setParams); - } + public String set(String key, String value, SetParams setParams) { + return jedisCommands.set(key, value, setParams); + } - @Override - public void del(String key) { - jedisCommands.del(key); - } + @Override + public void del(String key) { + jedisCommands.del(key); } + } } diff --git a/providers/redis/shedlock-provider-redis-jedis4/src/test/java/net/javacrumbs/shedlock/provider/redis/jedis4/JedisLockProviderIntegrationTest.java b/providers/redis/shedlock-provider-redis-jedis4/src/test/java/net/javacrumbs/shedlock/provider/redis/jedis4/JedisLockProviderIntegrationTest.java index cfe1e114f..a4337f48c 100644 --- a/providers/redis/shedlock-provider-redis-jedis4/src/test/java/net/javacrumbs/shedlock/provider/redis/jedis4/JedisLockProviderIntegrationTest.java +++ b/providers/redis/shedlock-provider-redis-jedis4/src/test/java/net/javacrumbs/shedlock/provider/redis/jedis4/JedisLockProviderIntegrationTest.java @@ -1,20 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.redis.jedis4; +import static net.javacrumbs.shedlock.provider.redis.jedis4.RedisContainer.ENV; +import static net.javacrumbs.shedlock.provider.redis.jedis4.RedisContainer.PORT; +import static org.assertj.core.api.Assertions.assertThat; + import net.javacrumbs.shedlock.core.ExtensibleLockProvider; import net.javacrumbs.shedlock.test.support.AbstractExtensibleLockProviderIntegrationTest; import org.junit.jupiter.api.BeforeEach; @@ -26,12 +28,8 @@ import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPool; -import static net.javacrumbs.shedlock.provider.redis.jedis4.RedisContainer.ENV; -import static net.javacrumbs.shedlock.provider.redis.jedis4.RedisContainer.PORT; -import static org.assertj.core.api.Assertions.assertThat; - @Testcontainers -public class JedisLockProviderIntegrationTest { +public class JedisLockProviderIntegrationTest { @Container public static final RedisContainer redis = new RedisContainer(PORT); @@ -47,6 +45,7 @@ public void createLockProvider() { jedisCluster = new JedisCluster(new HostAndPort(redis.getContainerIpAddress(), redis.getFirstMappedPort())); lockProvider = new JedisLockProvider(jedisCluster, ENV); } + @Override protected void assertUnlocked(String lockName) { assertThat(getLock(lockName)).isNull(); @@ -102,5 +101,4 @@ protected ExtensibleLockProvider getLockProvider() { return lockProvider; } } - } diff --git a/providers/redis/shedlock-provider-redis-jedis4/src/test/java/net/javacrumbs/shedlock/provider/redis/jedis4/RedisContainer.java b/providers/redis/shedlock-provider-redis-jedis4/src/test/java/net/javacrumbs/shedlock/provider/redis/jedis4/RedisContainer.java index b761dacff..c924eb873 100644 --- a/providers/redis/shedlock-provider-redis-jedis4/src/test/java/net/javacrumbs/shedlock/provider/redis/jedis4/RedisContainer.java +++ b/providers/redis/shedlock-provider-redis-jedis4/src/test/java/net/javacrumbs/shedlock/provider/redis/jedis4/RedisContainer.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.redis.jedis4; @@ -26,10 +24,9 @@ class RedisContainer extends FixedHostPortGenericContainer { private static final Logger LOGGER = LoggerFactory.getLogger(RedisContainer.class); - final static int PORT = 6379; - - final static String ENV = "test"; + static final int PORT = 6379; + static final String ENV = "test"; public RedisContainer(int hostPort) { super("redis:5-alpine"); @@ -40,12 +37,12 @@ public RedisContainer(int hostPort) { properties.requirepass = false; this.withFixedExposedPort(hostPort, PORT) - .withExposedPorts(PORT) - .withLogConsumer(frame -> LOGGER.info(frame.getUtf8String())) - .withCopyFileToContainer(MountableFile.forClasspathResource("redis.conf"), "/data/redis.conf") - .withCopyFileToContainer(MountableFile.forClasspathResource("nodes.conf"), "/data/nodes.conf") - .waitingFor(new RedisClusterStatusCheck(properties)) - //.waitingFor(new RedisStatusCheck(properties)) - .withCommand("redis-server", "/data/redis.conf"); + .withExposedPorts(PORT) + .withLogConsumer(frame -> LOGGER.info(frame.getUtf8String())) + .withCopyFileToContainer(MountableFile.forClasspathResource("redis.conf"), "/data/redis.conf") + .withCopyFileToContainer(MountableFile.forClasspathResource("nodes.conf"), "/data/nodes.conf") + .waitingFor(new RedisClusterStatusCheck(properties)) + // .waitingFor(new RedisStatusCheck(properties)) + .withCommand("redis-server", "/data/redis.conf"); } } diff --git a/providers/redis/shedlock-provider-redis-quarkus2/src/main/java/net/javacrumbs/shedlock/provider/redis/quarkus/QuarkusRedisLockProvider.java b/providers/redis/shedlock-provider-redis-quarkus2/src/main/java/net/javacrumbs/shedlock/provider/redis/quarkus/QuarkusRedisLockProvider.java index 117419189..c4be64863 100644 --- a/providers/redis/shedlock-provider-redis-quarkus2/src/main/java/net/javacrumbs/shedlock/provider/redis/quarkus/QuarkusRedisLockProvider.java +++ b/providers/redis/shedlock-provider-redis-quarkus2/src/main/java/net/javacrumbs/shedlock/provider/redis/quarkus/QuarkusRedisLockProvider.java @@ -1,8 +1,15 @@ package net.javacrumbs.shedlock.provider.redis.quarkus; +import static io.vertx.mutiny.redis.client.Command.SET; +import static net.javacrumbs.shedlock.support.Utils.getHostname; +import static net.javacrumbs.shedlock.support.Utils.toIsoString; + import io.quarkus.redis.datasource.RedisDataSource; import io.quarkus.redis.datasource.keys.KeyCommands; import io.vertx.mutiny.redis.client.Response; +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.ExtensibleLockProvider; @@ -11,16 +18,10 @@ import net.javacrumbs.shedlock.support.LockException; import net.javacrumbs.shedlock.support.annotation.NonNull; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; - -import static io.vertx.mutiny.redis.client.Command.SET; -import static net.javacrumbs.shedlock.support.Utils.getHostname; -import static net.javacrumbs.shedlock.support.Utils.toIsoString; - /** - * Uses Redis's `SET resource-name anystring NX EX max-lock-ms-time` as locking mechanism. + * Uses Redis's `SET resource-name anystring NX EX max-lock-ms-time` as locking + * mechanism. + * *

* See Set command */ @@ -33,7 +34,6 @@ public class QuarkusRedisLockProvider implements ExtensibleLockProvider { private final String keyPrefix; - public QuarkusRedisLockProvider(RedisDataSource dataSource) { this(dataSource, KEY_PREFIX_DEFAULT); } @@ -52,13 +52,12 @@ public Optional lock(@NonNull LockConfiguration lockConfiguration) { String key = buildKey(lockConfiguration.getName()); - Response response = redisDataSource.execute(SET, key, buildValue(), "NX", "PX", Long.toString(expireTime)); + Response response = redisDataSource.execute(SET, key, buildValue(), "NX", "PX", Long.toString(expireTime)); if (response != null && "OK".equals(response.toString())) { return Optional.of(new RedisLock(key, this, lockConfiguration)); } else { return Optional.empty(); } - } private Optional extend(LockConfiguration lockConfiguration) { @@ -81,15 +80,13 @@ String buildKey(String lockName) { } private boolean extendKeyExpiration(String key, long expiration) { - return keyCommands.pexpire(key,expiration); - + return keyCommands.pexpire(key, expiration); } private void deleteKey(String key) { keyCommands.del(key); } - private static final class RedisLock extends AbstractSimpleLock { private final String key; private final QuarkusRedisLockProvider quarkusLockProvider; @@ -130,6 +127,4 @@ private static long getMillisUntil(Instant instant) { private static String buildValue() { return String.format("ADDED:%s@%s", toIsoString(ClockProvider.now()), getHostname()); } - - } diff --git a/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/LockedService.java b/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/LockedService.java index d9ec5c881..ae2dad54b 100644 --- a/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/LockedService.java +++ b/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/LockedService.java @@ -1,13 +1,12 @@ package net.javacrumbs.shedlock.provider.redis.quarkus; +import java.util.concurrent.atomic.AtomicInteger; +import javax.enterprise.context.ApplicationScoped; import net.javacrumbs.shedlock.cdi.SchedulerLock; import net.javacrumbs.shedlock.core.LockAssert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.enterprise.context.ApplicationScoped; -import java.util.concurrent.atomic.AtomicInteger; - @ApplicationScoped public class LockedService { @@ -22,7 +21,6 @@ public void test() { execute(); LOG.info("Executing [DONE]"); - } public void execute() { @@ -30,7 +28,6 @@ public void execute() { LOG.info("Executing ....(c=" + count.get() + ")"); } - public int count() { LOG.info("getc=(" + count.get() + ")"); return count.get(); @@ -39,5 +36,4 @@ public int count() { public void countReset() { count.set(0); } - } diff --git a/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/QuarkusRedisLockProviderContainerTest.java b/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/QuarkusRedisLockProviderContainerTest.java index e9d17badd..03aee145c 100644 --- a/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/QuarkusRedisLockProviderContainerTest.java +++ b/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/QuarkusRedisLockProviderContainerTest.java @@ -1,15 +1,14 @@ package net.javacrumbs.shedlock.provider.redis.quarkus; +import static org.junit.jupiter.api.Assertions.assertEquals; + import io.quarkus.redis.datasource.RedisDataSource; import io.quarkus.test.junit.QuarkusTest; +import javax.inject.Inject; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; -import javax.inject.Inject; - -import static org.junit.jupiter.api.Assertions.assertEquals; - @QuarkusTest @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class QuarkusRedisLockProviderContainerTest { diff --git a/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/QuarkusRedisLockProviderIntegrationTest.java b/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/QuarkusRedisLockProviderIntegrationTest.java index e5a17c422..480bc315f 100644 --- a/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/QuarkusRedisLockProviderIntegrationTest.java +++ b/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/QuarkusRedisLockProviderIntegrationTest.java @@ -1,18 +1,16 @@ package net.javacrumbs.shedlock.provider.redis.quarkus; +import static org.assertj.core.api.Assertions.assertThat; + import io.quarkus.redis.datasource.RedisDataSource; import io.quarkus.redis.datasource.value.ValueCommands; import io.quarkus.test.junit.QuarkusTest; +import javax.inject.Inject; import net.javacrumbs.shedlock.core.ExtensibleLockProvider; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.test.support.AbstractExtensibleLockProviderIntegrationTest; import org.junit.jupiter.api.BeforeEach; -import javax.inject.Inject; - -import static org.assertj.core.api.Assertions.assertThat; - - @QuarkusTest public class QuarkusRedisLockProviderIntegrationTest extends AbstractExtensibleLockProviderIntegrationTest { @@ -47,6 +45,4 @@ private String getLock(String lockName) { protected ExtensibleLockProvider getLockProvider() { return (ExtensibleLockProvider) lockProvider; } - - } diff --git a/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/SchedulerLockFactory.java b/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/SchedulerLockFactory.java index 1f2716329..a4c6fe6f8 100644 --- a/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/SchedulerLockFactory.java +++ b/providers/redis/shedlock-provider-redis-quarkus2/src/test/java/net/javacrumbs/shedlock/provider/redis/quarkus/SchedulerLockFactory.java @@ -1,13 +1,11 @@ package net.javacrumbs.shedlock.provider.redis.quarkus; import io.quarkus.redis.datasource.RedisDataSource; -import net.javacrumbs.shedlock.core.LockProvider; -import org.eclipse.microprofile.config.inject.ConfigProperty; - import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import javax.inject.Singleton; - +import net.javacrumbs.shedlock.core.LockProvider; +import org.eclipse.microprofile.config.inject.ConfigProperty; @ApplicationScoped public class SchedulerLockFactory { diff --git a/providers/redis/shedlock-provider-redis-spring/src/main/java/net/javacrumbs/shedlock/provider/redis/spring/ReactiveRedisLockProvider.java b/providers/redis/shedlock-provider-redis-spring/src/main/java/net/javacrumbs/shedlock/provider/redis/spring/ReactiveRedisLockProvider.java index 7c4346c0d..b26cd615e 100644 --- a/providers/redis/shedlock-provider-redis-spring/src/main/java/net/javacrumbs/shedlock/provider/redis/spring/ReactiveRedisLockProvider.java +++ b/providers/redis/shedlock-provider-redis-spring/src/main/java/net/javacrumbs/shedlock/provider/redis/spring/ReactiveRedisLockProvider.java @@ -1,5 +1,11 @@ package net.javacrumbs.shedlock.provider.redis.spring; +import static net.javacrumbs.shedlock.support.Utils.getHostname; +import static net.javacrumbs.shedlock.support.Utils.toIsoString; + +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; @@ -10,16 +16,9 @@ import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; import org.springframework.data.redis.core.ReactiveStringRedisTemplate; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; - -import static net.javacrumbs.shedlock.support.Utils.getHostname; -import static net.javacrumbs.shedlock.support.Utils.toIsoString; - /** - * Uses Redis's `SET resource-name anystring NX PX max-lock-ms-time` as locking mechanism. - * See https://redis.io/commands/set + * Uses Redis's `SET resource-name anystring NX PX max-lock-ms-time` as locking + * mechanism. See https://redis.io/commands/set */ public class ReactiveRedisLockProvider implements LockProvider { private static final String KEY_PREFIX_DEFAULT = "job-lock"; @@ -36,9 +35,12 @@ public ReactiveRedisLockProvider(@NonNull ReactiveRedisConnectionFactory redisCo /** * Creates ReactiveRedisLockProvider * - * @param redisConn ReactiveRedisConnectionFactory - * @param environment environment is part of the key and thus makes sure there is not key conflict between - * multiple ShedLock instances running on the same Redis + * @param redisConn + * ReactiveRedisConnectionFactory + * @param environment + * environment is part of the key and thus makes sure there is not + * key conflict between multiple ShedLock instances running on the + * same Redis */ public ReactiveRedisLockProvider(@NonNull ReactiveRedisConnectionFactory redisConn, @NonNull String environment) { this(redisConn, environment, KEY_PREFIX_DEFAULT); @@ -47,24 +49,36 @@ public ReactiveRedisLockProvider(@NonNull ReactiveRedisConnectionFactory redisCo /** * Creates ReactiveRedisLockProvider * - * @param redisConn ReactiveRedisConnectionFactory - * @param environment environment is part of the key and thus makes sure there is not key conflict between - * multiple ShedLock instances running on the same Redis - * @param keyPrefix prefix of the key in Redis. + * @param redisConn + * ReactiveRedisConnectionFactory + * @param environment + * environment is part of the key and thus makes sure there is not + * key conflict between multiple ShedLock instances running on the + * same Redis + * @param keyPrefix + * prefix of the key in Redis. */ - public ReactiveRedisLockProvider(@NonNull ReactiveRedisConnectionFactory redisConn, @NonNull String environment, @NonNull String keyPrefix) { + public ReactiveRedisLockProvider( + @NonNull ReactiveRedisConnectionFactory redisConn, @NonNull String environment, @NonNull String keyPrefix) { this(new ReactiveStringRedisTemplate(redisConn), environment, keyPrefix); } /** * Create ReactiveRedisLockProvider * - * @param redisTemplate ReactiveStringRedisTemplate - * @param environment environment is part of the key and thus makes sure there is not key conflict between - * multiple ShedLock instances running on the same Redis - * @param keyPrefix prefix of the key in Redis. + * @param redisTemplate + * ReactiveStringRedisTemplate + * @param environment + * environment is part of the key and thus makes sure there is not + * key conflict between multiple ShedLock instances running on the + * same Redis + * @param keyPrefix + * prefix of the key in Redis. */ - public ReactiveRedisLockProvider(@NonNull ReactiveStringRedisTemplate redisTemplate, @NonNull String environment, @NonNull String keyPrefix) { + public ReactiveRedisLockProvider( + @NonNull ReactiveStringRedisTemplate redisTemplate, + @NonNull String environment, + @NonNull String keyPrefix) { this.redisTemplate = redisTemplate; this.environment = environment; this.keyPrefix = keyPrefix; @@ -77,7 +91,10 @@ public Optional lock(@NonNull LockConfiguration lockConfiguration) { String key = ReactiveRedisLock.createKey(keyPrefix, environment, lockConfiguration.getName()); String value = ReactiveRedisLock.createValue(now); Duration expirationTime = Duration.between(now, lockConfiguration.getLockAtMostUntil()); - Boolean lockResult = redisTemplate.opsForValue().setIfAbsent(key, value, expirationTime).block(); + Boolean lockResult = redisTemplate + .opsForValue() + .setIfAbsent(key, value, expirationTime) + .block(); if (Boolean.TRUE.equals(lockResult)) { return Optional.of(new ReactiveRedisLock(key, redisTemplate, lockConfiguration)); } @@ -96,7 +113,8 @@ private static String createValue(Instant now) { return String.format("ADDED:%s@%s", toIsoString(now), getHostname()); } - private ReactiveRedisLock(String key, ReactiveStringRedisTemplate redisTemplate, LockConfiguration lockConfiguration) { + private ReactiveRedisLock( + String key, ReactiveStringRedisTemplate redisTemplate, LockConfiguration lockConfiguration) { super(lockConfiguration); this.key = key; this.redisTemplate = redisTemplate; @@ -114,7 +132,10 @@ protected void doUnlock() { } } else { String value = createValue(now); - redisTemplate.opsForValue().setIfPresent(key, value, expirationTime).block(); + redisTemplate + .opsForValue() + .setIfPresent(key, value, expirationTime) + .block(); } } } diff --git a/providers/redis/shedlock-provider-redis-spring/src/main/java/net/javacrumbs/shedlock/provider/redis/spring/RedisLockProvider.java b/providers/redis/shedlock-provider-redis-spring/src/main/java/net/javacrumbs/shedlock/provider/redis/spring/RedisLockProvider.java index a2beedde4..53fd7a92a 100644 --- a/providers/redis/shedlock-provider-redis-spring/src/main/java/net/javacrumbs/shedlock/provider/redis/spring/RedisLockProvider.java +++ b/providers/redis/shedlock-provider-redis-spring/src/main/java/net/javacrumbs/shedlock/provider/redis/spring/RedisLockProvider.java @@ -1,20 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.redis.spring; +import static java.lang.Boolean.TRUE; +import static net.javacrumbs.shedlock.support.Utils.getHostname; +import static net.javacrumbs.shedlock.support.Utils.toIsoString; +import static org.springframework.data.redis.connection.RedisStringCommands.SetOption.SET_IF_ABSENT; + +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; +import java.util.concurrent.TimeUnit; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; @@ -28,19 +35,9 @@ import org.springframework.data.redis.core.types.Expiration; import org.springframework.data.redis.serializer.RedisSerializer; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; -import java.util.concurrent.TimeUnit; - -import static java.lang.Boolean.TRUE; -import static net.javacrumbs.shedlock.support.Utils.getHostname; -import static net.javacrumbs.shedlock.support.Utils.toIsoString; -import static org.springframework.data.redis.connection.RedisStringCommands.SetOption.SET_IF_ABSENT; - /** - * Uses Redis's `SET resource-name anystring NX PX max-lock-ms-time` as locking mechanism. - * See https://redis.io/commands/set + * Uses Redis's `SET resource-name anystring NX PX max-lock-ms-time` as locking + * mechanism. See https://redis.io/commands/set */ public class RedisLockProvider implements LockProvider { private static final String KEY_PREFIX_DEFAULT = "job-lock"; @@ -57,9 +54,12 @@ public RedisLockProvider(@NonNull RedisConnectionFactory redisConn) { /** * Creates RedisLockProvider * - * @param redisConn RedisConnectionFactory - * @param environment environment is part of the key and thus makes sure there is not key conflict between - * multiple ShedLock instances running on the same Redis + * @param redisConn + * RedisConnectionFactory + * @param environment + * environment is part of the key and thus makes sure there is not + * key conflict between multiple ShedLock instances running on the + * same Redis */ public RedisLockProvider(@NonNull RedisConnectionFactory redisConn, @NonNull String environment) { this(redisConn, environment, KEY_PREFIX_DEFAULT); @@ -68,24 +68,34 @@ public RedisLockProvider(@NonNull RedisConnectionFactory redisConn, @NonNull Str /** * Creates RedisLockProvider * - * @param redisConn RedisConnectionFactory - * @param environment environment is part of the key and thus makes sure there is not key conflict between - * multiple ShedLock instances running on the same Redis - * @param keyPrefix prefix of the key in Redis. + * @param redisConn + * RedisConnectionFactory + * @param environment + * environment is part of the key and thus makes sure there is not + * key conflict between multiple ShedLock instances running on the + * same Redis + * @param keyPrefix + * prefix of the key in Redis. */ - public RedisLockProvider(@NonNull RedisConnectionFactory redisConn, @NonNull String environment, @NonNull String keyPrefix) { + public RedisLockProvider( + @NonNull RedisConnectionFactory redisConn, @NonNull String environment, @NonNull String keyPrefix) { this(new StringRedisTemplate(redisConn), environment, keyPrefix); } /** * Create RedisLockProvider * - * @param redisTemplate StringRedisTemplate - * @param environment environment is part of the key and thus makes sure there is not key conflict between - * multiple ShedLock instances running on the same Redis - * @param keyPrefix prefix of the key in Redis. + * @param redisTemplate + * StringRedisTemplate + * @param environment + * environment is part of the key and thus makes sure there is not + * key conflict between multiple ShedLock instances running on the + * same Redis + * @param keyPrefix + * prefix of the key in Redis. */ - public RedisLockProvider(@NonNull StringRedisTemplate redisTemplate, @NonNull String environment, @NonNull String keyPrefix) { + public RedisLockProvider( + @NonNull StringRedisTemplate redisTemplate, @NonNull String environment, @NonNull String keyPrefix) { this.redisTemplate = redisTemplate; this.environment = environment; this.keyPrefix = keyPrefix; @@ -138,17 +148,20 @@ public void doUnlock() { } } - String buildKey(String lockName) { return String.format("%s:%s:%s", keyPrefix, environment, lockName); } - private static Boolean tryToSetExpiration(StringRedisTemplate template, String key, Expiration expiration, SetOption option) { - return template.execute(connection -> { - byte[] serializedKey = ((RedisSerializer) template.getKeySerializer()).serialize(key); - byte[] serializedValue = ((RedisSerializer) template.getValueSerializer()).serialize(String.format("ADDED:%s@%s", toIsoString(ClockProvider.now()), getHostname())); - return connection.set(serializedKey, serializedValue, expiration, option); - }, false); + private static Boolean tryToSetExpiration( + StringRedisTemplate template, String key, Expiration expiration, SetOption option) { + return template.execute( + connection -> { + byte[] serializedKey = ((RedisSerializer) template.getKeySerializer()).serialize(key); + byte[] serializedValue = ((RedisSerializer) template.getValueSerializer()) + .serialize(String.format("ADDED:%s@%s", toIsoString(ClockProvider.now()), getHostname())); + return connection.set(serializedKey, serializedValue, expiration, option); + }, + false); } public static class Builder { diff --git a/providers/redis/shedlock-provider-redis-spring/src/test/java/net/javacrumbs/shedlock/provider/redis/spring/AbstractReactiveRedisLockProviderIntegrationTest.java b/providers/redis/shedlock-provider-redis-spring/src/test/java/net/javacrumbs/shedlock/provider/redis/spring/AbstractReactiveRedisLockProviderIntegrationTest.java index 48ffb9e6a..3a6a9c727 100644 --- a/providers/redis/shedlock-provider-redis-spring/src/test/java/net/javacrumbs/shedlock/provider/redis/spring/AbstractReactiveRedisLockProviderIntegrationTest.java +++ b/providers/redis/shedlock-provider-redis-spring/src/test/java/net/javacrumbs/shedlock/provider/redis/spring/AbstractReactiveRedisLockProviderIntegrationTest.java @@ -1,24 +1,24 @@ package net.javacrumbs.shedlock.provider.redis.spring; +import static org.assertj.core.api.Assertions.assertThat; + import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.test.support.AbstractLockProviderIntegrationTest; import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; import org.springframework.data.redis.core.ReactiveStringRedisTemplate; -import static org.assertj.core.api.Assertions.assertThat; - public abstract class AbstractReactiveRedisLockProviderIntegrationTest extends AbstractLockProviderIntegrationTest { private final ReactiveRedisLockProvider lockProvider; private final ReactiveStringRedisTemplate redisTemplate; - private final static String ENV = "test"; - private final static String KEY_PREFIX = "test-prefix"; + private static final String ENV = "test"; + private static final String KEY_PREFIX = "test-prefix"; public AbstractReactiveRedisLockProviderIntegrationTest(ReactiveRedisConnectionFactory connectionFactory) { lockProvider = new ReactiveRedisLockProvider.Builder(connectionFactory) - .environment(ENV) - .keyPrefix(KEY_PREFIX) - .build(); + .environment(ENV) + .keyPrefix(KEY_PREFIX) + .build(); redisTemplate = new ReactiveStringRedisTemplate(connectionFactory); } diff --git a/providers/redis/shedlock-provider-redis-spring/src/test/java/net/javacrumbs/shedlock/provider/redis/spring/AbstractRedisLockProviderIntegrationTest.java b/providers/redis/shedlock-provider-redis-spring/src/test/java/net/javacrumbs/shedlock/provider/redis/spring/AbstractRedisLockProviderIntegrationTest.java index 7b6b22cf3..63c607ce0 100644 --- a/providers/redis/shedlock-provider-redis-spring/src/test/java/net/javacrumbs/shedlock/provider/redis/spring/AbstractRedisLockProviderIntegrationTest.java +++ b/providers/redis/shedlock-provider-redis-spring/src/test/java/net/javacrumbs/shedlock/provider/redis/spring/AbstractRedisLockProviderIntegrationTest.java @@ -1,41 +1,38 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.redis.spring; +import static org.assertj.core.api.Assertions.assertThat; + import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.test.support.AbstractLockProviderIntegrationTest; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; -import static org.assertj.core.api.Assertions.assertThat; - public abstract class AbstractRedisLockProviderIntegrationTest extends AbstractLockProviderIntegrationTest { private final RedisLockProvider lockProvider; private final StringRedisTemplate redisTemplate; - private final static String ENV = "test"; - private final static String KEY_PREFIX = "test-prefix"; - + private static final String ENV = "test"; + private static final String KEY_PREFIX = "test-prefix"; public AbstractRedisLockProviderIntegrationTest(RedisConnectionFactory connectionFactory) { lockProvider = new RedisLockProvider.Builder(connectionFactory) - .environment(ENV) - .keyPrefix(KEY_PREFIX) - .build(); + .environment(ENV) + .keyPrefix(KEY_PREFIX) + .build(); redisTemplate = new StringRedisTemplate(connectionFactory); } diff --git a/providers/redis/shedlock-provider-redis-spring/src/test/java/net/javacrumbs/shedlock/provider/redis/spring/SpringRedisLockProviderIntegrationTest.java b/providers/redis/shedlock-provider-redis-spring/src/test/java/net/javacrumbs/shedlock/provider/redis/spring/SpringRedisLockProviderIntegrationTest.java index a33b1d0dc..5ffc5bcf3 100644 --- a/providers/redis/shedlock-provider-redis-spring/src/test/java/net/javacrumbs/shedlock/provider/redis/spring/SpringRedisLockProviderIntegrationTest.java +++ b/providers/redis/shedlock-provider-redis-spring/src/test/java/net/javacrumbs/shedlock/provider/redis/spring/SpringRedisLockProviderIntegrationTest.java @@ -1,20 +1,19 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.redis.spring; +import java.io.IOException; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Nested; @@ -26,14 +25,11 @@ import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import redis.embedded.RedisServer; -import java.io.IOException; - public class SpringRedisLockProviderIntegrationTest { private static RedisServer redisServer; - private final static int PORT = 6381; - protected final static String HOST = "localhost"; - + private static final int PORT = 6381; + protected static final String HOST = "localhost"; @BeforeAll public static void startRedis() throws IOException { @@ -90,8 +86,7 @@ public Redisson() { private static RedisConnectionFactory createRedissonConnectionFactory() { Config config = new Config(); - config.useSingleServer() - .setAddress("redis://" + HOST + ":" + PORT); + config.useSingleServer().setAddress("redis://" + HOST + ":" + PORT); RedissonClient redisson = org.redisson.Redisson.create(config); return new RedissonConnectionFactory(redisson); } diff --git a/providers/zookeeper/shedlock-provider-zookeeper-curator/src/main/java/net/javacrumbs/shedlock/provider/zookeeper/curator/ZookeeperCuratorLockProvider.java b/providers/zookeeper/shedlock-provider-zookeeper-curator/src/main/java/net/javacrumbs/shedlock/provider/zookeeper/curator/ZookeeperCuratorLockProvider.java index 1c6c72213..b1a339cb8 100644 --- a/providers/zookeeper/shedlock-provider-zookeeper-curator/src/main/java/net/javacrumbs/shedlock/provider/zookeeper/curator/ZookeeperCuratorLockProvider.java +++ b/providers/zookeeper/shedlock-provider-zookeeper-curator/src/main/java/net/javacrumbs/shedlock/provider/zookeeper/curator/ZookeeperCuratorLockProvider.java @@ -1,20 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.zookeeper.curator; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Objects.requireNonNull; +import static net.javacrumbs.shedlock.support.Utils.toIsoString; + +import java.time.Instant; +import java.time.format.DateTimeParseException; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; @@ -30,17 +35,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Instant; -import java.time.format.DateTimeParseException; -import java.util.Optional; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static java.util.Objects.requireNonNull; -import static net.javacrumbs.shedlock.support.Utils.toIsoString; - /** - * Locks kept using ZooKeeper. When locking, creates a PERSISTENT node with node name = lock_name and value containing lock data, - * when unlocking, keeps the node and changes node data to release the lock. + * Locks kept using ZooKeeper. When locking, creates a PERSISTENT node with node + * name = lock_name and value containing lock data, when unlocking, keeps the + * node and changes node data to release the lock. */ public class ZookeeperCuratorLockProvider implements LockProvider { public static final String DEFAULT_PATH = "/shedlock"; @@ -84,9 +82,12 @@ public Optional lock(@NonNull LockConfiguration lockConfiguration) { } } - private Optional tryLock(LockConfiguration lockConfiguration, String nodePath, Stat stat) throws Exception { + private Optional tryLock(LockConfiguration lockConfiguration, String nodePath, Stat stat) + throws Exception { try { - client.setData().withVersion(stat.getVersion()).forPath(nodePath, serialize(lockConfiguration.getLockAtMostUntil())); + client.setData() + .withVersion(stat.getVersion()) + .forPath(nodePath, serialize(lockConfiguration.getLockAtMostUntil())); return Optional.of(new CuratorLock(nodePath, client, lockConfiguration)); } catch (KeeperException.BadVersionException e) { logger.trace("Node value can not be set, must have been set by a parallel process"); @@ -96,7 +97,10 @@ private Optional tryLock(LockConfiguration lockConfiguration, String private boolean createNode(LockConfiguration lockConfiguration, String nodePath) { try { - client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(nodePath, serialize(lockConfiguration.getLockAtMostUntil())); + client.create() + .creatingParentsIfNeeded() + .withMode(CreateMode.PERSISTENT) + .forPath(nodePath, serialize(lockConfiguration.getLockAtMostUntil())); return true; } catch (KeeperException.NodeExistsException e) { return false; diff --git a/providers/zookeeper/shedlock-provider-zookeeper-curator/src/test/java/net/javacrumbs/shedlock/provider/zookeeper/curator/ZookeeperCuratorLockProviderIntegrationTest.java b/providers/zookeeper/shedlock-provider-zookeeper-curator/src/test/java/net/javacrumbs/shedlock/provider/zookeeper/curator/ZookeeperCuratorLockProviderIntegrationTest.java index 81b2520e6..7719c392e 100644 --- a/providers/zookeeper/shedlock-provider-zookeeper-curator/src/test/java/net/javacrumbs/shedlock/provider/zookeeper/curator/ZookeeperCuratorLockProviderIntegrationTest.java +++ b/providers/zookeeper/shedlock-provider-zookeeper-curator/src/test/java/net/javacrumbs/shedlock/provider/zookeeper/curator/ZookeeperCuratorLockProviderIntegrationTest.java @@ -1,20 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.provider.zookeeper.curator; +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.util.Optional; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.SimpleLock; import net.javacrumbs.shedlock.test.support.AbstractLockProviderIntegrationTest; @@ -27,11 +29,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.IOException; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; - public class ZookeeperCuratorLockProviderIntegrationTest extends AbstractLockProviderIntegrationTest { private TestingServer zkTestServer; private CuratorFramework client; @@ -51,9 +48,11 @@ public void stopZookeeper() throws IOException { } private CuratorFramework newClient() { - CuratorFramework client = CuratorFrameworkFactory.builder().namespace("MyApp") - .retryPolicy(new RetryOneTime(2000)) - .connectString(zkTestServer.getConnectString()).build(); + CuratorFramework client = CuratorFrameworkFactory.builder() + .namespace("MyApp") + .retryPolicy(new RetryOneTime(2000)) + .connectString(zkTestServer.getConnectString()) + .build(); client.start(); return client; } @@ -78,7 +77,8 @@ protected LockProvider getLockProvider() { @Override protected void assertUnlocked(String lockName) { try { - assertThat(zookeeperCuratorLockProvider.isLocked(getNodePath(lockName))).isFalse(); + assertThat(zookeeperCuratorLockProvider.isLocked(getNodePath(lockName))) + .isFalse(); } catch (Exception e) { throw new IllegalStateException(e); } @@ -87,7 +87,8 @@ protected void assertUnlocked(String lockName) { @Override protected void assertLocked(String lockName) { try { - assertThat(zookeeperCuratorLockProvider.isLocked(getNodePath(lockName))).isTrue(); + assertThat(zookeeperCuratorLockProvider.isLocked(getNodePath(lockName))) + .isTrue(); } catch (Exception e) { throw new IllegalStateException(e); } diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/AbstractSimpleLock.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/AbstractSimpleLock.java index 8d0dd04a5..fbba062f0 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/AbstractSimpleLock.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/AbstractSimpleLock.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; @@ -38,7 +36,8 @@ public final void unlock() { @Override public Optional extend(Duration lockAtMostFor, Duration lockAtLeastFor) { checkValidity(); - Optional result = doExtend(new LockConfiguration(ClockProvider.now(), lockConfiguration.getName(), lockAtMostFor, lockAtLeastFor)); + Optional result = doExtend( + new LockConfiguration(ClockProvider.now(), lockConfiguration.getName(), lockAtMostFor, lockAtLeastFor)); valid = false; return result; } @@ -49,7 +48,8 @@ protected Optional doExtend(LockConfiguration newConfiguration) { private void checkValidity() { if (!valid) { - throw new IllegalStateException("Lock " + lockConfiguration.getName() + " is not valid, it has already been unlocked or extended"); + throw new IllegalStateException( + "Lock " + lockConfiguration.getName() + " is not valid, it has already been unlocked or extended"); } } } diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/ClockProvider.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/ClockProvider.java index b2ef45af9..be84e7d8d 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/ClockProvider.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/ClockProvider.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; @@ -19,9 +17,7 @@ import java.time.Instant; import java.time.temporal.ChronoUnit; -/** - * Enables to change Clock for all ShedLock classes - */ +/** Enables to change Clock for all ShedLock classes */ public class ClockProvider { private static Clock clock = Clock.systemUTC(); diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/DefaultLockManager.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/DefaultLockManager.java index 8daefd580..e87a3b241 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/DefaultLockManager.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/DefaultLockManager.java @@ -1,31 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Optional; - import static java.util.Objects.requireNonNull; +import java.util.Optional; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -/** - * Default implementation {@link LockManager} implementation. - */ +/** Default implementation {@link LockManager} implementation. */ public class DefaultLockManager implements LockManager { private static final Logger logger = LoggerFactory.getLogger(DefaultLockManager.class); @@ -36,7 +30,8 @@ public DefaultLockManager(LockProvider lockProvider, LockConfigurationExtractor this(new DefaultLockingTaskExecutor(lockProvider), lockConfigurationExtractor); } - public DefaultLockManager(LockingTaskExecutor lockingTaskExecutor, LockConfigurationExtractor lockConfigurationExtractor) { + public DefaultLockManager( + LockingTaskExecutor lockingTaskExecutor, LockConfigurationExtractor lockConfigurationExtractor) { this.lockingTaskExecutor = requireNonNull(lockingTaskExecutor); this.lockConfigurationExtractor = requireNonNull(lockConfigurationExtractor); } diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/DefaultLockingTaskExecutor.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/DefaultLockingTaskExecutor.java index 9856e38e3..3b694bfa0 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/DefaultLockingTaskExecutor.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/DefaultLockingTaskExecutor.java @@ -1,32 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static java.util.Objects.requireNonNull; +import static net.javacrumbs.shedlock.core.LockAssert.alreadyLockedBy; import java.time.Instant; import java.util.Optional; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import static java.util.Objects.requireNonNull; -import static net.javacrumbs.shedlock.core.LockAssert.alreadyLockedBy; - -/** - * Default {@link LockingTaskExecutor} implementation. - */ +/** Default {@link LockingTaskExecutor} implementation. */ public class DefaultLockingTaskExecutor implements LockingTaskExecutor { private static final Logger logger = LoggerFactory.getLogger(DefaultLockingTaskExecutor.class); private final LockProvider lockProvider; @@ -49,10 +44,12 @@ public void executeWithLock(Runnable task, LockConfiguration lockConfig) { @Override public void executeWithLock(Task task, LockConfiguration lockConfig) throws Throwable { - executeWithLock(() -> { - task.call(); - return null; - }, lockConfig); + executeWithLock( + () -> { + task.call(); + return null; + }, + lockConfig); } @Override @@ -68,7 +65,8 @@ public TaskResult executeWithLock(TaskWithResult task, LockConfigurati try { LockAssert.startLock(lockName); LockExtender.startLock(lock.get()); - logger.debug("Locked '{}', lock will be held at most until {}", lockName, lockConfig.getLockAtMostUntil()); + logger.debug( + "Locked '{}', lock will be held at most until {}", lockName, lockConfig.getLockAtMostUntil()); return TaskResult.result(task.call()); } finally { LockAssert.endLock(); @@ -76,7 +74,8 @@ public TaskResult executeWithLock(TaskWithResult task, LockConfigurati if (activeLock != null) { activeLock.unlock(); } else { - // This should never happen, but I do not know any better way to handle the null case. + // This should never happen, but I do not know any better way to handle the null + // case. logger.warn("No active lock, please report this as a bug."); lock.get().unlock(); } diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/ExtensibleLockProvider.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/ExtensibleLockProvider.java index 26902164f..cd9b43b7b 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/ExtensibleLockProvider.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/ExtensibleLockProvider.java @@ -1,22 +1,17 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; -/** - * Marker interface for a LockProvider that supports lock extension. - */ -public interface ExtensibleLockProvider extends LockProvider { -} +/** Marker interface for a LockProvider that supports lock extension. */ +public interface ExtensibleLockProvider extends LockProvider {} diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockAssert.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockAssert.java index d7c8c1022..0dd991f22 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockAssert.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockAssert.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; @@ -19,17 +17,20 @@ import java.util.LinkedList; /** - * Asserts lock presence. The Spring ecosystem is so complicated, so one can not be sure that the lock is applied. This class - * makes sure that the task is indeed locked. + * Asserts lock presence. The Spring ecosystem is so complicated, so one can not + * be sure that the lock is applied. This class makes sure that the task is + * indeed locked. + * *

- * If you use AOP with Kotlin, it does not have to work due to final methods, if you use TaskExecutor wrapper, it can be - * broken by Sleuth,. + * If you use AOP with Kotlin, it does not have to work due to final methods, if + * you use TaskExecutor wrapper, it can be broken by Sleuth,. */ public final class LockAssert { - // using null initial value so new LinkedList is not created every time we call alreadyLockedBy + // using null initial value so new LinkedList is not created every time we call + // alreadyLockedBy private static final ThreadLocal> activeLocksTL = ThreadLocal.withInitial(() -> null); - private LockAssert() { } + private LockAssert() {} static void startLock(String name) { activeLocks().add(name); @@ -55,9 +56,7 @@ private static Deque activeLocks() { return activeLocksTL.get(); } - /** - * Throws an exception if the lock is not present. - */ + /** Throws an exception if the lock is not present. */ public static void assertLocked() { Deque activeLocks = activeLocksTL.get(); if (activeLocks == null || activeLocks.isEmpty()) { @@ -70,10 +69,8 @@ public static class TestHelper { private static final String TEST_LOCK_NAME = "net.javacrumbs.shedlock.core.test-lock"; /** - * If pass is set to true, all LockAssert.assertLocked calls in current thread will pass. - * To be used in unit tests only - * - * + * If pass is set to true, all LockAssert.assertLocked calls in current thread + * will pass. To be used in unit tests only * LockAssert.TestHelper.makeAllAssertsPass(true) * */ diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockConfiguration.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockConfiguration.java index a2d1511b5..fe315c0e9 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockConfiguration.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockConfiguration.java @@ -1,48 +1,48 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; +import static net.javacrumbs.shedlock.core.ClockProvider.now; + import java.time.Duration; import java.time.Instant; import java.util.Objects; -import static net.javacrumbs.shedlock.core.ClockProvider.now; - -/** - * Lock configuration. - */ +/** Lock configuration. */ public class LockConfiguration { private final Instant createdAt; private final String name; /** - * The lock is held until this duration passes, after that it's automatically released (the process holding it has most likely - * died without releasing the lock) Can be ignored by providers which can detect dead processes (like Zookeeper) + * The lock is held until this duration passes, after that it's automatically + * released (the process holding it has most likely died without releasing the + * lock) Can be ignored by providers which can detect dead processes (like + * Zookeeper) */ private final Duration lockAtMostFor; /** - * The lock will be held at least this duration even if the task holding the lock finishes earlier. + * The lock will be held at least this duration even if the task holding the + * lock finishes earlier. */ private final Duration lockAtLeastFor; /** - * Creates LockConfiguration. There are two types of lock providers. One that uses "db time" which requires relative - * values of lockAtMostFor and lockAtLeastFor (currently it's only JdbcTemplateLockProvider). Second type of + * Creates LockConfiguration. There are two types of lock providers. One that + * uses "db time" which requires relative values of lockAtMostFor and + * lockAtLeastFor (currently it's only JdbcTemplateLockProvider). Second type of * lock provider uses absolute time calculated from `createdAt`. * * @param createdAt @@ -66,7 +66,6 @@ public LockConfiguration(Instant createdAt, String name, Duration lockAtMostFor, } } - public String getName() { return name; } @@ -79,9 +78,7 @@ public Instant getLockAtLeastUntil() { return createdAt.plus(lockAtLeastFor); } - /** - * Returns either now or lockAtLeastUntil whichever is later. - */ + /** Returns either now or lockAtLeastUntil whichever is later. */ public Instant getUnlockTime() { Instant now = now(); Instant lockAtLeastUntil = getLockAtLeastUntil(); @@ -98,10 +95,7 @@ public Duration getLockAtMostFor() { @Override public String toString() { - return "LockConfiguration{" + - "name='" + name + '\'' + - ", lockAtMostFor=" + lockAtMostFor + - ", lockAtLeastFor=" + lockAtLeastFor + - '}'; + return "LockConfiguration{" + "name='" + name + '\'' + ", lockAtMostFor=" + lockAtMostFor + ", lockAtLeastFor=" + + lockAtLeastFor + '}'; } } diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockConfigurationExtractor.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockConfigurationExtractor.java index 7e312b27b..a0934fcba 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockConfigurationExtractor.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockConfigurationExtractor.java @@ -1,25 +1,21 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; import java.util.Optional; -/** - * Extracts lock parameters from the task. - */ +/** Extracts lock parameters from the task. */ public interface LockConfigurationExtractor { - Optional getLockConfiguration(Runnable task); + Optional getLockConfiguration(Runnable task); } diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockExtender.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockExtender.java index 89fe558b6..aa670398a 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockExtender.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockExtender.java @@ -1,32 +1,38 @@ package net.javacrumbs.shedlock.core; -import net.javacrumbs.shedlock.support.annotation.Nullable; - import java.time.Duration; import java.util.Deque; import java.util.LinkedList; import java.util.Optional; +import net.javacrumbs.shedlock.support.annotation.Nullable; public final class LockExtender { - // Using deque here instead of a simple thread local to be able to handle nested locks. + // Using deque here instead of a simple thread local to be able to handle nested + // locks. private static final ThreadLocal> activeLocks = ThreadLocal.withInitial(LinkedList::new); - private LockExtender() { } + private LockExtender() {} /** - * Extends active lock. Is based on a thread local variable, so it might not work in case of async processing. - * In case of nested locks, extends the innermost lock. + * Extends active lock. Is based on a thread local variable, so it might not + * work in case of async processing. In case of nested locks, extends the + * innermost lock. * - * @throws LockCanNotBeExtendedException when the lock can not be extended due to expired lock - * @throws NoActiveLockException when there is no active lock in the thread local - * @throws UnsupportedOperationException when the LockProvider does not support lock extension. + * @throws LockCanNotBeExtendedException + * when the lock can not be extended due to expired lock + * @throws NoActiveLockException + * when there is no active lock in the thread local + * @throws UnsupportedOperationException + * when the LockProvider does not support lock extension. */ public static void extendActiveLock(Duration lockAtMostFor, Duration lockAtLeastFor) { SimpleLock lock = locks().peekLast(); if (lock == null) throw new NoActiveLockException(); Optional newLock = lock.extend(lockAtMostFor, lockAtLeastFor); if (newLock.isPresent()) { - // removing and adding here should be safe as it's a thread local variable and the changes are only visible in the current thread. + // removing and adding here should be safe as it's a thread local variable and + // the changes are + // only visible in the current thread. locks().removeLast(); locks().addLast(newLock.get()); } else { @@ -60,7 +66,8 @@ public LockExtensionException(String message) { public static class NoActiveLockException extends LockExtensionException { public NoActiveLockException() { - super("No active lock in current thread, please make sure that you execute LockExtender.extendActiveLock in locked context."); + super( + "No active lock in current thread, please make sure that you execute LockExtender.extendActiveLock in locked context."); } } diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockManager.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockManager.java index 7c17367c8..dd9e25967 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockManager.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockManager.java @@ -1,23 +1,19 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; -/** - * Executes task if not locked. - */ +/** Executes task if not locked. */ public interface LockManager { void executeWithLock(Runnable task); } diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockProvider.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockProvider.java index 104016680..500b47c5c 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockProvider.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockProvider.java @@ -1,30 +1,26 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; import java.util.Optional; -/** - * Provides lock implementation. - */ +/** Provides lock implementation. */ public interface LockProvider { /** - * @return If empty optional has been returned, lock could not be acquired. The lock - * has to be released by the callee. + * @return If empty optional has been returned, lock could not be acquired. The + * lock has to be released by the callee. */ Optional lock(LockConfiguration lockConfiguration); } diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockableRunnable.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockableRunnable.java index dd09147cc..283c44d05 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockableRunnable.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockableRunnable.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockingTaskExecutor.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockingTaskExecutor.java index 45101b1f8..7a1a4f831 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockingTaskExecutor.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/LockingTaskExecutor.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; @@ -18,16 +16,12 @@ import net.javacrumbs.shedlock.support.annotation.Nullable; public interface LockingTaskExecutor { - /** - * Executes task if it's not already running. - */ + /** Executes task if it's not already running. */ void executeWithLock(Runnable task, LockConfiguration lockConfig); void executeWithLock(Task task, LockConfiguration lockConfig) throws Throwable; - /** - * Executes task. - */ + /** Executes task. */ default TaskResult executeWithLock(TaskWithResult task, LockConfiguration lockConfig) throws Throwable { throw new UnsupportedOperationException(); } @@ -45,6 +39,7 @@ interface TaskWithResult { final class TaskResult { private final boolean executed; + @Nullable private final T result; diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/SimpleLock.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/SimpleLock.java index 9845f7e3b..2fbef0027 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/SimpleLock.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/core/SimpleLock.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; @@ -21,21 +19,26 @@ public interface SimpleLock { /** - * Unlocks the lock. Once you unlock it, you should not use for any other operation. + * Unlocks the lock. Once you unlock it, you should not use for any other + * operation. * - * @throws IllegalStateException if the lock has already been unlocked or extended + * @throws IllegalStateException + * if the lock has already been unlocked or extended */ void unlock(); /** - * Extends the lock. If the lock can be extended a new lock is returned. After calling extend, no other operation - * can be called on current lock. + * Extends the lock. If the lock can be extended a new lock is returned. After + * calling extend, no other operation can be called on current lock. + * *

* This method is NOT supported by all lock providers. * * @return a new lock or empty optional if the lock can not be extended - * @throws IllegalStateException if the lock has already been unlocked or extended - * @throws UnsupportedOperationException if the lock extension is not supported by LockProvider. + * @throws IllegalStateException + * if the lock has already been unlocked or extended + * @throws UnsupportedOperationException + * if the lock extension is not supported by LockProvider. */ default Optional extend(Duration lockAtMostFor, Duration lockAtLeastFor) { throw new UnsupportedOperationException(); diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/AbstractStorageAccessor.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/AbstractStorageAccessor.java index efe1ab76f..dbd3f798a 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/AbstractStorageAccessor.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/AbstractStorageAccessor.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.support; diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/KeepAliveLockProvider.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/KeepAliveLockProvider.java index 7f976be97..d40eae94e 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/KeepAliveLockProvider.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/KeepAliveLockProvider.java @@ -1,5 +1,13 @@ package net.javacrumbs.shedlock.support; +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static net.javacrumbs.shedlock.core.ClockProvider.now; + +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ExtensibleLockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; @@ -8,23 +16,20 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; - -import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static net.javacrumbs.shedlock.core.ClockProvider.now; - /** - * LockProvider that keeps the lock `alive`. In the middle of lockAtMostFor period tries to extend the lock for - * lockAtMostFor period. For example, if the lockAtMostFor is 10 minutes the lock is extended every 5 minutes for 10 minutes - * until the lock is released. If the process dies, the lock is automatically released after lockAtMostFor period as usual. + * LockProvider that keeps the lock `alive`. In the middle of lockAtMostFor + * period tries to extend the lock for lockAtMostFor period. For example, if the + * lockAtMostFor is 10 minutes the lock is extended every 5 minutes for 10 + * minutes until the lock is released. If the process dies, the lock is + * automatically released after lockAtMostFor period as usual. * - * Does not support lockAtMostFor shorter than 30s. The reason is that with short (subsecond) lockAtMostFor time the - * time when we attmpt to extend the lock is too close to the expiration time and the lock can expire before we are able to extend it. + *

+ * Does not support lockAtMostFor shorter than 30s. The reason is that + * with short (subsecond) lockAtMostFor time the time when we attmpt to extend + * the lock is too close to the expiration time and the lock can expire before + * we are able to extend it. * + *

* Wraps ExtensibleLockProvider that implements the actual locking. */ public class KeepAliveLockProvider implements LockProvider { @@ -38,7 +43,8 @@ public KeepAliveLockProvider(ExtensibleLockProvider wrapped, ScheduledExecutorSe this(wrapped, executorService, Duration.ofSeconds(30)); } - KeepAliveLockProvider(ExtensibleLockProvider wrapped, ScheduledExecutorService executorService, Duration minimalLockAtMostFor) { + KeepAliveLockProvider( + ExtensibleLockProvider wrapped, ScheduledExecutorService executorService, Duration minimalLockAtMostFor) { this.wrapped = wrapped; this.executorService = executorService; this.minimalLockAtMostFor = minimalLockAtMostFor; @@ -47,7 +53,8 @@ public KeepAliveLockProvider(ExtensibleLockProvider wrapped, ScheduledExecutorSe @Override public Optional lock(LockConfiguration lockConfiguration) { if (lockConfiguration.getLockAtMostFor().compareTo(minimalLockAtMostFor) < 0) { - throw new IllegalArgumentException("Can not use KeepAliveLockProvider with lockAtMostFor shorter than " + minimalLockAtMostFor); + throw new IllegalArgumentException( + "Can not use KeepAliveLockProvider with lockAtMostFor shorter than " + minimalLockAtMostFor); } Optional lock = wrapped.lock(lockConfiguration); return lock.map(simpleLock -> new KeepAliveLock(lockConfiguration, simpleLock, executorService)); @@ -61,7 +68,8 @@ private static class KeepAliveLock extends AbstractSimpleLock { private boolean active = true; private Instant currentLockAtMostUntil; - private KeepAliveLock(LockConfiguration lockConfiguration, SimpleLock lock, ScheduledExecutorService executorService) { + private KeepAliveLock( + LockConfiguration lockConfiguration, SimpleLock lock, ScheduledExecutorService executorService) { super(lockConfiguration); this.lock = lock; this.lockExtensionPeriod = lockConfiguration.getLockAtMostFor().dividedBy(2); @@ -70,22 +78,23 @@ private KeepAliveLock(LockConfiguration lockConfiguration, SimpleLock lock, Sche long extensionPeriodMs = lockExtensionPeriod.toMillis(); this.future = executorService.scheduleAtFixedRate( - this::extendForNextPeriod, - extensionPeriodMs, - extensionPeriodMs, - MILLISECONDS - ); + this::extendForNextPeriod, extensionPeriodMs, extensionPeriodMs, MILLISECONDS); } private void extendForNextPeriod() { - // We can have a race-condition when we extend the lock but the `lock` field is accessed before we update it. + // We can have a race-condition when we extend the lock but the `lock` field is + // accessed + // before we update it. synchronized (this) { if (!active) { return; } if (currentLockAtMostUntil.isBefore(now())) { - // Failsafe for cases when we are not able to extend the lock and it expires before the extension - // In such case someone else might have already obtained the lock so we can't extend it. + // Failsafe for cases when we are not able to extend the lock and it expires + // before the + // extension + // In such case someone else might have already obtained the lock so we can't + // extend it. stop(); return; } @@ -94,10 +103,14 @@ private void extendForNextPeriod() { remainingLockAtLeastFor = Duration.ZERO; } currentLockAtMostUntil = now().plus(lockConfiguration.getLockAtMostFor()); - Optional extendedLock = lock.extend(lockConfiguration.getLockAtMostFor(), remainingLockAtLeastFor); + Optional extendedLock = + lock.extend(lockConfiguration.getLockAtMostFor(), remainingLockAtLeastFor); if (extendedLock.isPresent()) { lock = extendedLock.get(); - logger.trace("Lock {} extended for {}", lockConfiguration.getName(), lockConfiguration.getLockAtMostFor()); + logger.trace( + "Lock {} extended for {}", + lockConfiguration.getName(), + lockConfiguration.getLockAtMostFor()); } else { logger.warn("Can't extend lock {}", lockConfiguration.getName()); stop(); diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/LockException.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/LockException.java index cd39fbb94..4fda2f038 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/LockException.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/LockException.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.support; diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/LockRecordRegistry.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/LockRecordRegistry.java index 523d51dd2..fe469e768 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/LockRecordRegistry.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/LockRecordRegistry.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.support; @@ -20,8 +18,9 @@ import java.util.WeakHashMap; /** - * Some LockProviders have to decide if a new record has to be created or an old one updated. - * This class helps them keep track of existing lock records, so they know if a lock record exists. + * Some LockProviders have to decide if a new record has to be created or an old + * one updated. This class helps them keep track of existing lock records, so + * they know if a lock record exists. */ class LockRecordRegistry { private final Set lockRecords = Collections.synchronizedSet(Collections.newSetFromMap(new WeakHashMap<>())); @@ -34,7 +33,6 @@ void removeLockRecord(String lockName) { lockRecords.remove(lockName); } - public boolean lockRecordRecentlyCreated(String lockName) { return lockRecords.contains(lockName); } diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/StorageAccessor.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/StorageAccessor.java index 5767a9348..363ca0e4b 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/StorageAccessor.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/StorageAccessor.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.support; @@ -21,16 +19,19 @@ public interface StorageAccessor { /** * Inserts a record, if it does not already exists. If it exists, returns false. * - * @param lockConfiguration LockConfiguration + * @param lockConfiguration + * LockConfiguration * @return true if inserted */ boolean insertRecord(LockConfiguration lockConfiguration); /** - * Tries to update the lock record. If there is already a valid lock record (the lock is held by someone else) - * update should not do anything and this method returns false. + * Tries to update the lock record. If there is already a valid lock record (the + * lock is held by someone else) update should not do anything and this method + * returns false. * - * @param lockConfiguration LockConfiguration + * @param lockConfiguration + * LockConfiguration * @return true if updated */ boolean updateRecord(LockConfiguration lockConfiguration); diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/StorageBasedLockProvider.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/StorageBasedLockProvider.java index cec1afb80..c539f9a92 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/StorageBasedLockProvider.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/StorageBasedLockProvider.java @@ -1,45 +1,40 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.support; +import java.util.Optional; import net.javacrumbs.shedlock.core.AbstractSimpleLock; import net.javacrumbs.shedlock.core.ExtensibleLockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.SimpleLock; -import java.util.Optional; - /** * Distributed lock using abstract storage + * *

- * It uses a table/collection that contains ID = lock name and a field locked_until. + * It uses a table/collection that contains ID = lock name and a field + * locked_until. + * *

    - *
  1. - * Attempts to insert a new lock record. As an optimization, we keep in-memory track of created lock records. If the record - * has been inserted, returns lock. - *
  2. - *
  3. - * We will try to update lock record using filter ID == name AND lock_until <= now - *
  4. - *
  5. - * If the update succeeded (1 updated row/document), we have the lock. If the update failed (0 updated documents) somebody else holds the lock - *
  6. - *
  7. - * When unlocking, lock_until is set to now. - *
  8. + *
  9. Attempts to insert a new lock record. As an optimization, we keep + * in-memory track of created lock records. If the record has been inserted, + * returns lock. + *
  10. We will try to update lock record using filter ID == name AND lock_until + * <= now + *
  11. If the update succeeded (1 updated row/document), we have the lock. If + * the update failed (0 updated documents) somebody else holds the lock + *
  12. When unlocking, lock_until is set to now. *
*/ public class StorageBasedLockProvider implements ExtensibleLockProvider { @@ -50,9 +45,7 @@ protected StorageBasedLockProvider(StorageAccessor storageAccessor) { this.storageAccessor = storageAccessor; } - /** - * Clears cache of existing lock records. - */ + /** Clears cache of existing lock records. */ public void clearCache() { lockRecordRegistry.clear(); } @@ -81,7 +74,9 @@ protected boolean doLock(LockConfiguration lockConfiguration) { // we were able to create the record, we have the lock return true; } - // we were not able to create the record, it already exists, let's put it to the cache so we do not try again + // we were not able to create the record, it already exists, let's put it to the + // cache so we + // do not try again lockRecordRegistry.addLockRecord(name); } @@ -90,9 +85,13 @@ protected boolean doLock(LockConfiguration lockConfiguration) { return storageAccessor.updateRecord(lockConfiguration); } catch (Exception e) { // There are some users that start the app before they have the DB ready. - // If they use JDBC, insertRecord returns false, the record is stored in the recordRegistry - // and the insert is not attempted again. We are assuming that the DB still does not exist - // when update is attempted. Unlike insert, update throws the exception, and we clear the cache here. + // If they use JDBC, insertRecord returns false, the record is stored in the + // recordRegistry + // and the insert is not attempted again. We are assuming that the DB still does + // not exist + // when update is attempted. Unlike insert, update throws the exception, and we + // clear the + // cache here. if (tryToCreateLockRecord) { lockRecordRegistry.removeLockRecord(name); } @@ -122,5 +121,4 @@ public Optional doExtend(LockConfiguration newConfig) { } } } - } diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/Utils.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/Utils.java index db36a80c2..8e861ad23 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/Utils.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/Utils.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.support; @@ -26,10 +24,13 @@ public final class Utils { /** * A {@link DateTimeFormatter} like {@link DateTimeFormatter#ISO_INSTANT} with - * the exception that it always appends exactly three fractional digits (nano seconds). + * the exception that it always appends exactly three fractional digits (nano + * seconds). + * *

- * This is required in order to guarantee natural sorting, which enables us to use - * <= comparision in queries. + * This is required in order to guarantee natural sorting, which enables us to + * use <= + * comparision in queries. * *

      * 2018-12-07T12:30:37.000Z
@@ -37,10 +38,12 @@ public final class Utils {
      * 2018-12-07T12:30:37.819Z
      * 2018-12-07T12:30:37.820Z
      * 
+ * *

- * When using variable fractional digit count as done in {@link DateTimeFormatter#ISO_INSTANT ISO_INSTANT} - * and {@link DateTimeFormatter#ISO_OFFSET_DATE_TIME ISO_OFFSET_DATE_TIME} the following sorting - * occurs: + * When using variable fractional digit count as done in + * {@link DateTimeFormatter#ISO_INSTANT ISO_INSTANT} and + * {@link DateTimeFormatter#ISO_OFFSET_DATE_TIME ISO_OFFSET_DATE_TIME} the + * following sorting occurs: * *

      * 2018-12-07T12:30:37.819Z
@@ -49,18 +52,17 @@ public final class Utils {
      * 2018-12-07T12:30:37Z
      * 
* - * @see natural sorting of ISO 8601 time format + * @see natural sorting of ISO + * 8601 time format */ private static final DateTimeFormatter formatter = new DateTimeFormatterBuilder() - .parseCaseInsensitive() - .appendInstant(3) - .toFormatter(); - + .parseCaseInsensitive() + .appendInstant(3) + .toFormatter(); private static final String hostname = initHostname(); - private Utils() { - } + private Utils() {} public static String getHostname() { return hostname; diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/NonNull.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/NonNull.java index 193b30515..8accacde5 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/NonNull.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/NonNull.java @@ -1,29 +1,28 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.support.annotation; -import javax.annotation.Nonnull; -import javax.annotation.meta.TypeQualifierNickname; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import javax.annotation.Nonnull; +import javax.annotation.meta.TypeQualifierNickname; /** - * A common annotation to declare that annotated elements cannot be {@code null}. + * A common annotation to declare that annotated elements cannot be + * {@code null}. * * @see Nullable */ @@ -31,5 +30,4 @@ @Retention(RetentionPolicy.RUNTIME) @Nonnull @TypeQualifierNickname -public @interface NonNull { -} +public @interface NonNull {} diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/NonNullApi.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/NonNullApi.java index 1c90870ff..2ed18240a 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/NonNullApi.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/NonNullApi.java @@ -1,21 +1,23 @@ package net.javacrumbs.shedlock.support.annotation; -import javax.annotation.Nonnull; -import javax.annotation.meta.TypeQualifierDefault; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import javax.annotation.Nonnull; +import javax.annotation.meta.TypeQualifierDefault; /** - * A common annotation to declare that parameters and return values - * are to be considered as non-nullable by default for a given package. + * A common annotation to declare that parameters and return values are to be + * considered as non-nullable by default for a given package. * - *

Leverages JSR-305 meta-annotations to indicate nullability in Java to common + *

+ * Leverages JSR-305 meta-annotations to indicate nullability in Java to common * tools with JSR-305 support and used by Kotlin to infer nullability of API. * - *

Should be used at package level in association with {@link Nullable} + *

+ * Should be used at package level in association with {@link Nullable} * annotations at parameter and return value level. * * @author Sebastien Deleuze @@ -29,5 +31,4 @@ @Documented @Nonnull @TypeQualifierDefault({ElementType.METHOD, ElementType.PARAMETER}) -public @interface NonNullApi { -} +public @interface NonNullApi {} diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/NonNullFields.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/NonNullFields.java index d805ac304..ebb7d00b3 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/NonNullFields.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/NonNullFields.java @@ -1,21 +1,23 @@ package net.javacrumbs.shedlock.support.annotation; -import javax.annotation.Nonnull; -import javax.annotation.meta.TypeQualifierDefault; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import javax.annotation.Nonnull; +import javax.annotation.meta.TypeQualifierDefault; /** * A common annotation to declare that fields are to be considered as * non-nullable by default for a given package. * - *

Leverages JSR-305 meta-annotations to indicate nullability in Java to common - * tools with JSR-305 support and used by Kotlin to infer nullability API. + *

+ * Leverages JSR-305 meta-annotations to indicate nullability in Java to common + * tools with JSR-305 support and used by Kotlin to infer nullability API. * - *

Should be used at package level in association with {@link Nullable} + *

+ * Should be used at package level in association with {@link Nullable} * annotations at field level. * * @author Sebastien Deleuze @@ -28,5 +30,4 @@ @Documented @Nonnull @TypeQualifierDefault(ElementType.FIELD) -public @interface NonNullFields { -} +public @interface NonNullFields {} diff --git a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/Nullable.java b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/Nullable.java index 6e4514940..c32cb8b6e 100644 --- a/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/Nullable.java +++ b/shedlock-core/src/main/java/net/javacrumbs/shedlock/support/annotation/Nullable.java @@ -1,35 +1,32 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.support.annotation; -import javax.annotation.Nonnull; -import javax.annotation.meta.TypeQualifierNickname; -import javax.annotation.meta.When; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import javax.annotation.Nonnull; +import javax.annotation.meta.TypeQualifierNickname; +import javax.annotation.meta.When; /** - * A common annotation to declare that annotated elements can be {@code null} under - * some circumstance. + * A common annotation to declare that annotated elements can be {@code null} + * under some circumstance. */ @Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Nonnull(when = When.MAYBE) @TypeQualifierNickname -public @interface Nullable { -} +public @interface Nullable {} diff --git a/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/DefaultLockManagerTest.java b/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/DefaultLockManagerTest.java index 346d48a06..bf698323a 100644 --- a/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/DefaultLockManagerTest.java +++ b/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/DefaultLockManagerTest.java @@ -1,27 +1,18 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; - -import org.junit.jupiter.api.Test; -import org.mockito.InOrder; - -import java.time.Duration; -import java.util.Optional; - import static net.javacrumbs.shedlock.core.ClockProvider.now; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -29,16 +20,22 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.time.Duration; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + class DefaultLockManagerTest { - private static final LockConfiguration LOCK_CONFIGURATION = new LockConfiguration(now(),"name", Duration.ofSeconds(10), Duration.ZERO); + private static final LockConfiguration LOCK_CONFIGURATION = + new LockConfiguration(now(), "name", Duration.ofSeconds(10), Duration.ZERO); private final LockProvider lockProvider = mock(LockProvider.class); private final LockConfigurationExtractor lockConfigurationExtractor = mock(LockConfigurationExtractor.class); private final Runnable task = mock(Runnable.class); private final SimpleLock lock = mock(SimpleLock.class); - private final DefaultLockManager defaultLockManager = new DefaultLockManager(lockProvider, lockConfigurationExtractor); - + private final DefaultLockManager defaultLockManager = + new DefaultLockManager(lockProvider, lockConfigurationExtractor); @Test void noConfigNoLock() { @@ -69,5 +66,4 @@ void doNotExecuteIfAlreadyLocked() { defaultLockManager.executeWithLock(task); verifyNoInteractions(task); } - } diff --git a/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/DefaultLockingTaskExecutorTest.java b/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/DefaultLockingTaskExecutorTest.java index 3e828c999..d2c32098d 100644 --- a/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/DefaultLockingTaskExecutorTest.java +++ b/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/DefaultLockingTaskExecutorTest.java @@ -1,37 +1,36 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; -import net.javacrumbs.shedlock.core.LockingTaskExecutor.TaskResult; -import org.junit.jupiter.api.Test; - -import java.time.Duration; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; - import static net.javacrumbs.shedlock.core.ClockProvider.now; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.time.Duration; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; +import net.javacrumbs.shedlock.core.LockingTaskExecutor.TaskResult; +import org.junit.jupiter.api.Test; + class DefaultLockingTaskExecutorTest { private final LockProvider lockProvider = mock(LockProvider.class); private final DefaultLockingTaskExecutor executor = new DefaultLockingTaskExecutor(lockProvider); - private final LockConfiguration lockConfig = new LockConfiguration(now(),"test", Duration.ofSeconds(100), Duration.ZERO); - private final LockConfiguration lockConfig2 = new LockConfiguration(now(),"test2", Duration.ofSeconds(100), Duration.ZERO); + private final LockConfiguration lockConfig = + new LockConfiguration(now(), "test", Duration.ofSeconds(100), Duration.ZERO); + private final LockConfiguration lockConfig2 = + new LockConfiguration(now(), "test2", Duration.ofSeconds(100), Duration.ZERO); @Test void lockShouldBeReentrant() { @@ -39,7 +38,8 @@ void lockShouldBeReentrant() { AtomicBoolean called = new AtomicBoolean(false); - executor.executeWithLock((Runnable) () -> executor.executeWithLock((Runnable) () -> called.set(true), lockConfig), lockConfig); + executor.executeWithLock( + (Runnable) () -> executor.executeWithLock((Runnable) () -> called.set(true), lockConfig), lockConfig); assertThat(called.get()).isTrue(); } @@ -51,14 +51,14 @@ void lockShouldBeReentrantForMultipleDifferentLocks() { AtomicBoolean called = new AtomicBoolean(false); - executor.executeWithLock((Runnable) () -> executor.executeWithLock((Runnable) () -> called.set(true), lockConfig2), lockConfig); + executor.executeWithLock( + (Runnable) () -> executor.executeWithLock((Runnable) () -> called.set(true), lockConfig2), lockConfig); assertThat(called.get()).isTrue(); } private void mockLockFor(LockConfiguration lockConfig2) { - when(lockProvider.lock(lockConfig2)) - .thenReturn(Optional.of(mock(SimpleLock.class))); + when(lockProvider.lock(lockConfig2)).thenReturn(Optional.of(mock(SimpleLock.class))); } @Test diff --git a/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/LockAssertTest.java b/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/LockAssertTest.java index 420d1166e..9ec9a7699 100644 --- a/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/LockAssertTest.java +++ b/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/LockAssertTest.java @@ -1,25 +1,18 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; -import org.junit.jupiter.api.Test; - -import java.time.Duration; -import java.util.Optional; - import static net.javacrumbs.shedlock.core.ClockProvider.now; import static net.javacrumbs.shedlock.core.LockAssert.alreadyLockedBy; import static org.assertj.core.api.Assertions.assertThat; @@ -27,6 +20,10 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.time.Duration; +import java.util.Optional; +import org.junit.jupiter.api.Test; + class LockAssertTest { @Test @@ -36,15 +33,14 @@ void assertLockedShouldFailIfLockNotHeld() { @Test void assertLockedShouldNotFailIfLockHeld() { - LockConfiguration lockConfiguration = new LockConfiguration(now(), "test", Duration.ofSeconds(10), Duration.ZERO); + LockConfiguration lockConfiguration = + new LockConfiguration(now(), "test", Duration.ofSeconds(10), Duration.ZERO); LockProvider lockProvider = mock(LockProvider.class); when(lockProvider.lock(lockConfiguration)).thenReturn(Optional.of(mock(SimpleLock.class))); - new DefaultLockingTaskExecutor(lockProvider).executeWithLock( - (Runnable) LockAssert::assertLocked, - lockConfiguration - ); + new DefaultLockingTaskExecutor(lockProvider) + .executeWithLock((Runnable) LockAssert::assertLocked, lockConfiguration); } @Test diff --git a/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/LockConfigurationTest.java b/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/LockConfigurationTest.java index 650b8718a..0c005cec7 100644 --- a/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/LockConfigurationTest.java +++ b/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/LockConfigurationTest.java @@ -1,48 +1,46 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; -import org.junit.jupiter.api.Test; - import static java.time.Duration.ZERO; import static java.time.Duration.ofMillis; import static java.time.Duration.ofSeconds; import static net.javacrumbs.shedlock.core.ClockProvider.now; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import org.junit.jupiter.api.Test; class LockConfigurationTest { @Test void lockAtLeastUntilShouldBeBeforeOrEqualsToLockAtMostUntil() { new LockConfiguration(now(), "name", ZERO, ZERO); - new LockConfiguration(now(),"name", ofMillis(1), ZERO); + new LockConfiguration(now(), "name", ofMillis(1), ZERO); - assertThatThrownBy(() -> new LockConfiguration(now(),"name", ZERO, ofMillis(1))).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new LockConfiguration(now(), "name", ZERO, ofMillis(1))) + .isInstanceOf(IllegalArgumentException.class); } @Test void lockAtMostUntilHasToBeInTheFuture() { - assertThatThrownBy(() -> new LockConfiguration(now(),"name", ofSeconds(-1), ZERO)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new LockConfiguration(now(), "name", ofSeconds(-1), ZERO)) + .isInstanceOf(IllegalArgumentException.class); } - @Test void nameShouldNotBeEmpty() { - assertThatThrownBy(() -> new LockConfiguration(now(),"", ofSeconds(5), ofSeconds(5))).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new LockConfiguration(now(), "", ofSeconds(5), ofSeconds(5))) + .isInstanceOf(IllegalArgumentException.class); } - } diff --git a/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/LockExtenderTest.java b/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/LockExtenderTest.java index ab841b628..0d2ee1c3c 100644 --- a/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/LockExtenderTest.java +++ b/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/LockExtenderTest.java @@ -1,14 +1,5 @@ package net.javacrumbs.shedlock.core; -import net.javacrumbs.shedlock.core.LockExtender.LockCanNotBeExtendedException; -import net.javacrumbs.shedlock.core.LockExtender.NoActiveLockException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; - import static java.time.Duration.ZERO; import static java.time.Duration.ofSeconds; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -16,10 +7,18 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; +import net.javacrumbs.shedlock.core.LockExtender.LockCanNotBeExtendedException; +import net.javacrumbs.shedlock.core.LockExtender.NoActiveLockException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + class LockExtenderTest { private final LockProvider lockProvider = mock(LockProvider.class); private final SimpleLock lock = mock(SimpleLock.class); - private final SimpleLock newLock = mock(SimpleLock.class); + private final SimpleLock newLock = mock(SimpleLock.class); private final DefaultLockingTaskExecutor executor = new DefaultLockingTaskExecutor(lockProvider); private final LockConfiguration configuration = new LockConfiguration(Instant.now(), "test", ofSeconds(1), ZERO); private final Duration extendBy = ofSeconds(1); @@ -76,12 +75,12 @@ void shouldFailIfLockCanNotBeExtended() { Runnable task = () -> LockExtender.extendActiveLock(extendBy, ZERO); assertThatThrownBy(() -> executor.executeWithLock(task, configuration)) - .isInstanceOf(LockCanNotBeExtendedException.class); + .isInstanceOf(LockCanNotBeExtendedException.class); } @Test void shouldFailIfNoActiveLock() { assertThatThrownBy(() -> LockExtender.extendActiveLock(ofSeconds(1), ofSeconds(0))) - .isInstanceOf(NoActiveLockException.class); + .isInstanceOf(NoActiveLockException.class); } } diff --git a/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/ReentrantLockProvider.java b/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/ReentrantLockProvider.java index 69c1fe08c..a1a2c30d3 100644 --- a/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/ReentrantLockProvider.java +++ b/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/ReentrantLockProvider.java @@ -1,28 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; -import net.javacrumbs.shedlock.support.annotation.NonNull; - import java.util.Optional; import java.util.concurrent.locks.ReentrantLock; +import net.javacrumbs.shedlock.support.annotation.NonNull; /** - * Lock provider based on {@link java.util.concurrent.locks.ReentrantLock}. Only one task per - * SimpleLockProvider can be running. Useful mainly for testing. + * Lock provider based on {@link java.util.concurrent.locks.ReentrantLock}. Only + * one task per SimpleLockProvider can be running. Useful mainly for testing. */ public class ReentrantLockProvider implements LockProvider { private final ReentrantLock lock = new ReentrantLock(); diff --git a/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/ReentrantLockProviderTest.java b/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/ReentrantLockProviderTest.java index f0eda7a46..71b1a2d24 100644 --- a/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/ReentrantLockProviderTest.java +++ b/shedlock-core/src/test/java/net/javacrumbs/shedlock/core/ReentrantLockProviderTest.java @@ -1,22 +1,23 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.core; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.time.Duration; import java.util.Optional; @@ -26,23 +27,21 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; - -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; class ReentrantLockProviderTest { private final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10); private final LockProvider lockProvider = new ReentrantLockProvider(); private final LockConfigurationExtractor lockConfigurationExtractor = mock(LockConfigurationExtractor.class); private final LockManager lockManager = new DefaultLockManager(lockProvider, lockConfigurationExtractor); - private final LockConfiguration configuration = new LockConfiguration(now(),"test", Duration.ofSeconds(60), Duration.ZERO); + private final LockConfiguration configuration = + new LockConfiguration(now(), "test", Duration.ofSeconds(60), Duration.ZERO); @BeforeEach void configureMocks() { - when(lockConfigurationExtractor.getLockConfiguration(any(Runnable.class))).thenReturn(Optional.of(configuration)); + when(lockConfigurationExtractor.getLockConfiguration(any(Runnable.class))) + .thenReturn(Optional.of(configuration)); } @Test @@ -65,8 +64,10 @@ void shouldNotExecuteTwiceAtTheSameTime() throws ExecutionException, Interrupted assertThat(runningTasks.decrementAndGet()).isEqualTo(0); executedTasks.incrementAndGet(); }; - ScheduledFuture scheduledFuture1 = executor.schedule(new LockableRunnable(task, lockManager), 1, TimeUnit.MILLISECONDS); - ScheduledFuture scheduledFuture2 = executor.schedule(new LockableRunnable(task, lockManager), 1, TimeUnit.MILLISECONDS); + ScheduledFuture scheduledFuture1 = + executor.schedule(new LockableRunnable(task, lockManager), 1, TimeUnit.MILLISECONDS); + ScheduledFuture scheduledFuture2 = + executor.schedule(new LockableRunnable(task, lockManager), 1, TimeUnit.MILLISECONDS); scheduledFuture1.get(); scheduledFuture2.get(); @@ -81,5 +82,4 @@ private void sleep(int millis) { throw new RuntimeException(e); } } - } diff --git a/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/KeepAliveLockProviderTest.java b/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/KeepAliveLockProviderTest.java index f6f105bb9..2fcd7f97a 100644 --- a/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/KeepAliveLockProviderTest.java +++ b/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/KeepAliveLockProviderTest.java @@ -1,15 +1,5 @@ package net.javacrumbs.shedlock.support; -import net.javacrumbs.shedlock.core.ExtensibleLockProvider; -import net.javacrumbs.shedlock.core.LockConfiguration; -import net.javacrumbs.shedlock.core.SimpleLock; -import org.jmock.lib.concurrent.DeterministicScheduler; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.time.Duration; -import java.util.Optional; - import static java.time.Duration.ZERO; import static java.time.Duration.ofMillis; import static java.time.Duration.ofSeconds; @@ -23,11 +13,21 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import java.time.Duration; +import java.util.Optional; +import net.javacrumbs.shedlock.core.ExtensibleLockProvider; +import net.javacrumbs.shedlock.core.LockConfiguration; +import net.javacrumbs.shedlock.core.SimpleLock; +import org.jmock.lib.concurrent.DeterministicScheduler; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + class KeepAliveLockProviderTest { private final ExtensibleLockProvider wrappedProvider = mock(ExtensibleLockProvider.class); private final DeterministicScheduler scheduler = new DeterministicScheduler(); private final KeepAliveLockProvider provider = new KeepAliveLockProvider(wrappedProvider, scheduler, ofSeconds(1)); - private final LockConfiguration lockConfiguration = new LockConfiguration(now(), "lock", ofSeconds(3), ofSeconds(2)); + private final LockConfiguration lockConfiguration = + new LockConfiguration(now(), "lock", ofSeconds(3), ofSeconds(2)); private final SimpleLock originalLock = mock(SimpleLock.class); @BeforeEach @@ -81,7 +81,7 @@ void shouldCancelIfCanNotExtend() { @Test void shouldFailForShortLockAtMostFor() { assertThatThrownBy(() -> provider.lock(new LockConfiguration(now(), "short", ofMillis(100), ZERO))) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); } private void tickMs(int i) { diff --git a/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/LockRecordRegistryTest.java b/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/LockRecordRegistryTest.java index 19700b15a..453e62b25 100644 --- a/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/LockRecordRegistryTest.java +++ b/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/LockRecordRegistryTest.java @@ -1,25 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.support; -import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; import java.util.UUID; - -import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.Test; class LockRecordRegistryTest { private static final String NAME = "name"; diff --git a/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/StorageBasedLockProviderTest.java b/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/StorageBasedLockProviderTest.java index 651bbb4bc..a14a9360a 100644 --- a/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/StorageBasedLockProviderTest.java +++ b/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/StorageBasedLockProviderTest.java @@ -1,26 +1,18 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.support; -import net.javacrumbs.shedlock.core.LockConfiguration; -import org.junit.jupiter.api.Test; - -import java.time.Duration; -import java.time.temporal.ChronoUnit; - import static net.javacrumbs.shedlock.core.ClockProvider.now; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -31,8 +23,14 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import net.javacrumbs.shedlock.core.LockConfiguration; +import org.junit.jupiter.api.Test; + class StorageBasedLockProviderTest { - private static final LockConfiguration LOCK_CONFIGURATION = new LockConfiguration(now(),"name", Duration.of(5, ChronoUnit.MINUTES), Duration.ZERO); + private static final LockConfiguration LOCK_CONFIGURATION = + new LockConfiguration(now(), "name", Duration.of(5, ChronoUnit.MINUTES), Duration.ZERO); private static final LockException LOCK_EXCEPTION = new LockException("Test"); private final StorageAccessor storageAccessor = mock(StorageAccessor.class); diff --git a/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/UtilsTest.java b/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/UtilsTest.java index e1ed7b84b..aa873fa0a 100644 --- a/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/UtilsTest.java +++ b/shedlock-core/src/test/java/net/javacrumbs/shedlock/support/UtilsTest.java @@ -1,27 +1,23 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.support; -import org.junit.jupiter.api.Test; - -import java.time.Instant; - import static net.javacrumbs.shedlock.support.Utils.toIsoString; import static org.assertj.core.api.Assertions.assertThat; +import java.time.Instant; +import org.junit.jupiter.api.Test; class UtilsTest { diff --git a/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/AbstractExtensibleLockProviderIntegrationTest.java b/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/AbstractExtensibleLockProviderIntegrationTest.java index 73165f051..351c96c2e 100644 --- a/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/AbstractExtensibleLockProviderIntegrationTest.java +++ b/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/AbstractExtensibleLockProviderIntegrationTest.java @@ -1,33 +1,30 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support; -import net.javacrumbs.shedlock.core.ExtensibleLockProvider; -import net.javacrumbs.shedlock.core.SimpleLock; -import org.assertj.core.api.ThrowableAssert; -import org.junit.jupiter.api.Test; - -import java.time.Duration; -import java.util.Optional; - import static java.time.Duration.ZERO; import static java.time.Duration.ofSeconds; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.time.Duration; +import java.util.Optional; +import net.javacrumbs.shedlock.core.ExtensibleLockProvider; +import net.javacrumbs.shedlock.core.SimpleLock; +import org.assertj.core.api.ThrowableAssert; +import org.junit.jupiter.api.Test; + public abstract class AbstractExtensibleLockProviderIntegrationTest extends AbstractLockProviderIntegrationTest { private final Duration originalLockDuration = ofSeconds(2); @@ -46,11 +43,11 @@ public void shouldBeAbleToExtendLock() { newLock.unlock(); assertUnlocked(LOCK_NAME1); } + @Test public void shouldBeAbleToExtendMultipleTimes() { SimpleLock lock = lock(originalLockDuration); - SimpleLock newLock = extendLock(extendLock(extendLock(lock))); // wait for the original lock to be released @@ -60,7 +57,6 @@ public void shouldBeAbleToExtendMultipleTimes() { assertUnlocked(LOCK_NAME1); } - @Test public void shouldNotBeAbleToExtendUnlockedLock() { SimpleLock lock = lock(originalLockDuration); @@ -80,7 +76,6 @@ public void shouldNotBeAbleToExtendExpiredLock() { assertUnlocked(LOCK_NAME1); } - @Test public void shouldBeAbleToExtendAtLeast() { SimpleLock lock = lock(ofSeconds(10)); @@ -109,6 +104,7 @@ public void lockCanNotBeUnlockedAfterExtending() { private SimpleLock extendLock(SimpleLock lock) { return extendLock(lock, ZERO); } + private SimpleLock extendLock(SimpleLock lock, Duration lockAtLeastFor) { Optional newLock = lock.extend(ofSeconds(10), lockAtLeastFor); assertThat(newLock).isNotEmpty(); diff --git a/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/AbstractLockProviderIntegrationTest.java b/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/AbstractLockProviderIntegrationTest.java index 9ff2b1453..5f6954591 100644 --- a/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/AbstractLockProviderIntegrationTest.java +++ b/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/AbstractLockProviderIntegrationTest.java @@ -1,35 +1,32 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support; -import net.javacrumbs.shedlock.core.ClockProvider; -import net.javacrumbs.shedlock.core.LockConfiguration; -import net.javacrumbs.shedlock.core.LockProvider; -import net.javacrumbs.shedlock.core.SimpleLock; -import org.junit.jupiter.api.Test; +import static java.lang.Thread.sleep; +import static java.time.temporal.ChronoUnit.MINUTES; +import static java.time.temporal.ChronoUnit.SECONDS; +import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ExecutionException; - -import static java.lang.Thread.sleep; -import static java.time.temporal.ChronoUnit.MINUTES; -import static java.time.temporal.ChronoUnit.SECONDS; -import static org.assertj.core.api.Assertions.assertThat; +import net.javacrumbs.shedlock.core.ClockProvider; +import net.javacrumbs.shedlock.core.LockConfiguration; +import net.javacrumbs.shedlock.core.LockProvider; +import net.javacrumbs.shedlock.core.SimpleLock; +import org.junit.jupiter.api.Test; public abstract class AbstractLockProviderIntegrationTest { protected final String LOCK_NAME1 = UUID.randomUUID().toString(); @@ -97,12 +94,12 @@ protected void doTestTimeout(Duration lockAtMostFor) throws InterruptedException sleep(lockAtMostFor.toMillis() * 2); assertUnlocked(LOCK_NAME1); - Optional lock2 = getLockProvider().lock(lockConfig(LOCK_NAME1, Duration.ofMillis(50), Duration.ZERO)); + Optional lock2 = + getLockProvider().lock(lockConfig(LOCK_NAME1, Duration.ofMillis(50), Duration.ZERO)); assertThat(lock2).isNotEmpty(); lock2.get().unlock(); } - @Test public void shouldBeAbleToLockRightAfterUnlock() { LockConfiguration lockConfiguration = lockConfig(LOCK_NAME1); @@ -126,20 +123,26 @@ public void shouldLockAtLeastFor() throws InterruptedException { } protected void doTestShouldLockAtLeastFor(int sleepForMs) throws InterruptedException { - // Lock for LOCK_AT_LEAST_FOR - we do not expect the lock to be released before this time - Optional lock1 = getLockProvider().lock(lockConfig(LOCK_NAME1, LOCK_AT_LEAST_FOR.multipliedBy(2), LOCK_AT_LEAST_FOR)); + // Lock for LOCK_AT_LEAST_FOR - we do not expect the lock to be released before + // this time + Optional lock1 = + getLockProvider().lock(lockConfig(LOCK_NAME1, LOCK_AT_LEAST_FOR.multipliedBy(2), LOCK_AT_LEAST_FOR)); assertThat(lock1).describedAs("Should be locked").isNotEmpty(); lock1.get().unlock(); // Even though we have unlocked the lock, it will be held for some time - assertThat(getLockProvider().lock(lockConfig(LOCK_NAME1))).describedAs(getClass().getName() + "Can not acquire lock, grace period did not pass yet").isEmpty(); + assertThat(getLockProvider().lock(lockConfig(LOCK_NAME1))) + .describedAs(getClass().getName() + "Can not acquire lock, grace period did not pass yet") + .isEmpty(); // Let's wait for the lock to be automatically released sleep(LOCK_AT_LEAST_FOR.toMillis() + sleepForMs); // Should be able to acquire now Optional lock3 = getLockProvider().lock(lockConfig(LOCK_NAME1)); - assertThat(lock3).describedAs(getClass().getName() + "Can acquire the lock after grace period").isNotEmpty(); + assertThat(lock3) + .describedAs(getClass().getName() + "Can acquire the lock after grace period") + .isNotEmpty(); lock3.get().unlock(); } @@ -157,5 +160,5 @@ protected static LockConfiguration lockConfig(String name) { protected static LockConfiguration lockConfig(String name, Duration lockAtMostFor, Duration lockAtLeastFor) { return new LockConfiguration(ClockProvider.now(), name, lockAtMostFor, lockAtLeastFor); - } + } } diff --git a/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/AbstractStorageBasedLockProviderIntegrationTest.java b/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/AbstractStorageBasedLockProviderIntegrationTest.java index 660dbbba3..59bc53570 100644 --- a/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/AbstractStorageBasedLockProviderIntegrationTest.java +++ b/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/AbstractStorageBasedLockProviderIntegrationTest.java @@ -1,35 +1,32 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Optional; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.SimpleLock; import net.javacrumbs.shedlock.support.StorageBasedLockProvider; import org.junit.jupiter.api.Test; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; - -public abstract class AbstractStorageBasedLockProviderIntegrationTest extends AbstractExtensibleLockProviderIntegrationTest { +public abstract class AbstractStorageBasedLockProviderIntegrationTest + extends AbstractExtensibleLockProviderIntegrationTest { @Override protected abstract StorageBasedLockProvider getLockProvider(); - @Test public void lockShouldSurviveCacheClearingInTheMiddle() { StorageBasedLockProvider provider = getLockProvider(); diff --git a/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/FuzzTester.java b/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/FuzzTester.java index c9238f585..6a9122d5d 100644 --- a/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/FuzzTester.java +++ b/shedlock-test-support/src/main/java/net/javacrumbs/shedlock/test/support/FuzzTester.java @@ -1,27 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.support; -import net.javacrumbs.shedlock.core.ClockProvider; -import net.javacrumbs.shedlock.core.DefaultLockingTaskExecutor; -import net.javacrumbs.shedlock.core.LockConfiguration; -import net.javacrumbs.shedlock.core.LockProvider; -import net.javacrumbs.shedlock.core.LockingTaskExecutor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static java.time.temporal.ChronoUnit.MINUTES; +import static java.util.stream.Collectors.toList; +import static java.util.stream.IntStream.range; +import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import java.time.temporal.ChronoUnit; @@ -32,14 +27,17 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; - -import static java.time.temporal.ChronoUnit.MINUTES; -import static java.util.stream.Collectors.toList; -import static java.util.stream.IntStream.range; -import static org.assertj.core.api.Assertions.assertThat; +import net.javacrumbs.shedlock.core.ClockProvider; +import net.javacrumbs.shedlock.core.DefaultLockingTaskExecutor; +import net.javacrumbs.shedlock.core.LockConfiguration; +import net.javacrumbs.shedlock.core.LockProvider; +import net.javacrumbs.shedlock.core.LockingTaskExecutor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * Increments counter from several threads coordinating using lock provided under test. + * Increments counter from several threads coordinating using lock provided + * under test. */ public class FuzzTester { @@ -60,12 +58,7 @@ public FuzzTester(LockProvider lockProvider) { this(lockProvider, Duration.ofMillis(1), Duration.of(5, MINUTES), 100); } - public FuzzTester( - LockProvider lockProvider, - Duration sleepFor, - Duration lockAtMostFor, - int iterations - ) { + public FuzzTester(LockProvider lockProvider, Duration sleepFor, Duration lockAtMostFor, int iterations) { this.lockProvider = lockProvider; this.sleepFor = sleepFor; this.lockAtMostFor = lockAtMostFor; @@ -80,9 +73,9 @@ public void doFuzzTest() throws InterruptedException, ExecutionException { Job job1 = new Job("lock1", lockAtMostFor); Job job2 = new Job("lock2", lockAtMostFor); - List> tasks = range(0, THREADS).mapToObj(i -> (Callable) () -> - task(iters[i], i % 2 == 0 ? job1 : job2)).collect(toList() - ); + List> tasks = range(0, THREADS) + .mapToObj(i -> (Callable) () -> task(iters[i], i % 2 == 0 ? job1 : job2)) + .collect(toList()); waitForIt(executor.invokeAll(tasks)); assertThat(job2.getCounter()).isEqualTo(THREADS / 2 * iterations); @@ -98,16 +91,20 @@ private void waitForIt(List> futures) throws InterruptedException, protected Void task(int iterations, Job job) { try { - for (AtomicInteger i = new AtomicInteger(0); i.get() < iterations;) { - lockingTaskExecutor.executeWithLock((Runnable) () -> { - int n = job.getCounter(); - if (shouldLog()) logger.debug("action=getLock value={} i={}", n, i); - sleep(); - if (shouldLog()) logger.debug("action=setCounter value={} i={}", n + 1, i); - // counter is shared variable. If locking does not work, this overwrites the value set by another thread - job.setCounter(n + 1); - i.incrementAndGet(); - }, job.getLockConfiguration()); + for (AtomicInteger i = new AtomicInteger(0); i.get() < iterations; ) { + lockingTaskExecutor.executeWithLock( + (Runnable) () -> { + int n = job.getCounter(); + if (shouldLog()) logger.debug("action=getLock value={} i={}", n, i); + sleep(); + if (shouldLog()) logger.debug("action=setCounter value={} i={}", n + 1, i); + // counter is shared variable. If locking does not work, this overwrites the + // value + // set by another thread + job.setCounter(n + 1); + i.incrementAndGet(); + }, + job.getLockConfiguration()); } logger.debug("action=finished"); return null; @@ -145,11 +142,7 @@ protected static class Job { public LockConfiguration getLockConfiguration() { return new LockConfiguration( - ClockProvider.now(), - lockName, - lockAtMostFor, - Duration.of(5, ChronoUnit.MILLIS) - ); + ClockProvider.now(), lockName, lockAtMostFor, Duration.of(5, ChronoUnit.MILLIS)); } public int getCounter() { @@ -161,5 +154,3 @@ public void setCounter(int counter) { } } } - - diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/ExtendedLockConfigurationExtractor.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/ExtendedLockConfigurationExtractor.java index cc6102970..818d16162 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/ExtendedLockConfigurationExtractor.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/ExtendedLockConfigurationExtractor.java @@ -1,29 +1,24 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring; -import net.javacrumbs.shedlock.core.LockConfiguration; -import net.javacrumbs.shedlock.core.LockConfigurationExtractor; - import java.lang.reflect.Method; import java.util.Optional; +import net.javacrumbs.shedlock.core.LockConfiguration; +import net.javacrumbs.shedlock.core.LockConfigurationExtractor; public interface ExtendedLockConfigurationExtractor extends LockConfigurationExtractor { - /** - * Extracts lock configuration for given method - */ + /** Extracts lock configuration for given method */ Optional getLockConfiguration(Object object, Method method, Object[] parameterValues); } diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/LockableTaskScheduler.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/LockableTaskScheduler.java index 96ebaa93a..301723038 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/LockableTaskScheduler.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/LockableTaskScheduler.java @@ -1,35 +1,33 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring; -import net.javacrumbs.shedlock.core.LockManager; -import net.javacrumbs.shedlock.core.LockableRunnable; -import org.springframework.beans.factory.DisposableBean; -import org.springframework.scheduling.TaskScheduler; -import org.springframework.scheduling.Trigger; +import static java.util.Objects.requireNonNull; import java.time.Duration; import java.time.Instant; import java.util.Date; import java.util.concurrent.ScheduledFuture; - -import static java.util.Objects.requireNonNull; +import net.javacrumbs.shedlock.core.LockManager; +import net.javacrumbs.shedlock.core.LockableRunnable; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.Trigger; /** - * Wraps a all tasks to {@link LockableRunnable} and delegates all calls to a {@link TaskScheduler}. + * Wraps a all tasks to {@link LockableRunnable} and delegates all calls to a + * {@link TaskScheduler}. */ public class LockableTaskScheduler implements TaskScheduler, DisposableBean { private final TaskScheduler taskScheduler; diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/annotation/EnableSchedulerLock.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/annotation/EnableSchedulerLock.java index 09bfc8d8f..6669f5170 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/annotation/EnableSchedulerLock.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/annotation/EnableSchedulerLock.java @@ -1,29 +1,26 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.annotation; -import net.javacrumbs.shedlock.spring.aop.SchedulerLockConfigurationSelector; -import org.springframework.context.annotation.AdviceMode; -import org.springframework.context.annotation.Import; -import org.springframework.core.Ordered; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import net.javacrumbs.shedlock.spring.aop.SchedulerLockConfigurationSelector; +import org.springframework.context.annotation.AdviceMode; +import org.springframework.context.annotation.Import; +import org.springframework.core.Ordered; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @@ -31,51 +28,60 @@ public @interface EnableSchedulerLock { enum InterceptMode { /** - * Default mode when a TaskScheduler is wrapped in a proxy to ensure locking. Only applies lock - * if the {@link net.javacrumbs.shedlock.spring.annotation.SchedulerLock} annotated method is called using scheduler. + * Default mode when a TaskScheduler is wrapped in a proxy to ensure locking. + * Only applies lock if the + * {@link net.javacrumbs.shedlock.spring.annotation.SchedulerLock} annotated + * method is called using scheduler. */ PROXY_SCHEDULER, /** * Scheduled method is proxied to ensure locking. Lock is created every time - * {@link net.javacrumbs.shedlock.spring.annotation.SchedulerLock} annotated is called (even if it is NOT called using Spring scheduler) + * {@link net.javacrumbs.shedlock.spring.annotation.SchedulerLock} annotated is + * called (even if it is NOT called using Spring scheduler) */ PROXY_METHOD } - /** - * Mode of integration, either TaskScheduler is wrapped in a proxy or the scheduled method is proxied to ensure locking + * Mode of integration, either TaskScheduler is wrapped in a proxy or the + * scheduled method is proxied to ensure locking * - * @see Modes of Spring integration + * @see Modes + * of Spring integration */ InterceptMode interceptMode() default InterceptMode.PROXY_METHOD; - /** - * Default value how long the lock should be kept in case the machine which obtained the lock died before releasing it. - * Can be either time with suffix like 10s or ISO8601 duration as described in {@link java.time.Duration#parse(CharSequence)}, for example PT30S. - * This is just a fallback, under normal circumstances the lock is released as soon the tasks finishes. - * Set this to some value much higher than normal task duration. Can be overridden in each ScheduledLock annotation. - + * Default value how long the lock should be kept in case the machine which + * obtained the lock died before releasing it. Can be either time with suffix + * like 10s or ISO8601 duration as described in + * {@link java.time.Duration#parse(CharSequence)}, for example PT30S. This is + * just a fallback, under normal circumstances the lock is released as soon the + * tasks finishes. Set this to some value much higher than normal task duration. + * Can be overridden in each ScheduledLock annotation. */ String defaultLockAtMostFor(); - /** - * The lock will be held at least for this duration. - * Can be either time with suffix like 10s or ISO8601 duration as described in {@link java.time.Duration#parse(CharSequence)}, for example PT30S. Can be used if you really need to execute the task - * at most once in given period of time. If the duration of the task is shorter than clock difference between nodes, the task can - * be theoretically executed more than once (one node after another). By setting this parameter, you can make sure that the - * lock will be kept at least for given period of time. Can be overridden in each ScheduledLock annotation. + * The lock will be held at least for this duration. Can be either time with + * suffix like 10s or ISO8601 duration as described in + * {@link java.time.Duration#parse(CharSequence)}, for example PT30S. Can be + * used if you really need to execute the task at most once in given period of + * time. If the duration of the task is shorter than clock difference between + * nodes, the task can be theoretically executed more than once (one node after + * another). By setting this parameter, you can make sure that the lock will be + * kept at least for given period of time. Can be overridden in each + * ScheduledLock annotation. */ String defaultLockAtLeastFor() default "PT0S"; - /** - * Since 3.0.0 use {@link #interceptMode()} to configure the intercept mode. Had to be renamed to make it compatible - * with Spring AOP infrastructure. Sorry. + * Since 3.0.0 use {@link #interceptMode()} to configure the intercept mode. Had + * to be renamed to make it compatible with Spring AOP infrastructure. Sorry. * + *

* Indicate how advice should be applied. */ AdviceMode mode() default AdviceMode.PROXY; @@ -87,9 +93,11 @@ enum InterceptMode { boolean proxyTargetClass() default false; /** - * Indicate the ordering of the execution of the locking advisor - * when multiple advices are applied at a specific joinpoint. - *

The default is {@link Ordered#LOWEST_PRECEDENCE}. + * Indicate the ordering of the execution of the locking advisor when multiple + * advices are applied at a specific joinpoint. + * + *

+ * The default is {@link Ordered#LOWEST_PRECEDENCE}. */ int order() default Ordered.LOWEST_PRECEDENCE; } diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/annotation/SchedulerLock.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/annotation/SchedulerLock.java index 1a073748e..c032937de 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/annotation/SchedulerLock.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/annotation/SchedulerLock.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.annotation; @@ -23,28 +21,31 @@ @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface SchedulerLock { - /** - * Lock name. - */ + /** Lock name. */ String name() default ""; - /** - * How long the lock should be kept in case the machine which obtained the lock died before releasing it. - * This is just a fallback, under normal circumstances the lock is released as soon the tasks finishes. + * How long the lock should be kept in case the machine which obtained the lock + * died before releasing it. This is just a fallback, under normal circumstances + * the lock is released as soon the tasks finishes. * - * Can be either time with suffix like 10s or ISO8601 duration as described in {@link java.time.Duration#parse(CharSequence)}, for example PT30S. + *

+ * Can be either time with suffix like 10s or ISO8601 duration as described in + * {@link java.time.Duration#parse(CharSequence)}, for example PT30S. */ String lockAtMostFor() default ""; - /** - * The lock will be held at least for given duration. Can be used if you really need to execute the task - * at most once in given period of time. If the duration of the task is shorter than clock difference between nodes, the task can - * be theoretically executed more than once (one node after another). By setting this parameter, you can make sure that the - * lock will be kept at least for given period of time. + * The lock will be held at least for given duration. Can be used if you really + * need to execute the task at most once in given period of time. If the + * duration of the task is shorter than clock difference between nodes, the task + * can be theoretically executed more than once (one node after another). By + * setting this parameter, you can make sure that the lock will be kept at least + * for given period of time. * - * Can be either time with suffix like 10s or ISO8601 duration as described in {@link java.time.Duration#parse(CharSequence)}, for example PT30S. + *

+ * Can be either time with suffix like 10s or ISO8601 duration as described in + * {@link java.time.Duration#parse(CharSequence)}, for example PT30S. */ String lockAtLeastFor() default ""; } diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/AbstractLockConfiguration.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/AbstractLockConfiguration.java index 0491f1cba..fd8146421 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/AbstractLockConfiguration.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/AbstractLockConfiguration.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; @@ -26,10 +24,10 @@ abstract class AbstractLockConfiguration implements ImportAware { @Override public void setImportMetadata(AnnotationMetadata importMetadata) { this.annotationAttributes = AnnotationAttributes.fromMap( - importMetadata.getAnnotationAttributes(EnableSchedulerLock.class.getName(), false)); + importMetadata.getAnnotationAttributes(EnableSchedulerLock.class.getName(), false)); if (this.annotationAttributes == null) { throw new IllegalArgumentException( - "@EnableSchedulerLock is not present on importing class " + importMetadata.getClassName()); + "@EnableSchedulerLock is not present on importing class " + importMetadata.getClassName()); } } diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/LockConfigurationExtractorConfiguration.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/LockConfigurationExtractorConfiguration.java index 2c1272f25..a92b3a96a 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/LockConfigurationExtractorConfiguration.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/LockConfigurationExtractorConfiguration.java @@ -1,31 +1,26 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; +import java.time.Duration; import net.javacrumbs.shedlock.spring.ExtendedLockConfigurationExtractor; import org.springframework.context.EmbeddedValueResolverAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringValueResolver; -import java.time.Duration; - -/** - * Defines ExtendedLockConfigurationExtractor bean. - */ +/** Defines ExtendedLockConfigurationExtractor bean. */ @Configuration class LockConfigurationExtractorConfiguration extends AbstractLockConfiguration implements EmbeddedValueResolverAware { private final StringToDurationConverter durationConverter = StringToDurationConverter.INSTANCE; @@ -34,7 +29,8 @@ class LockConfigurationExtractorConfiguration extends AbstractLockConfiguration @Bean ExtendedLockConfigurationExtractor lockConfigurationExtractor() { - return new SpringLockConfigurationExtractor(defaultLockAtMostForDuration(), defaultLockAtLeastForDuration(), resolver, durationConverter); + return new SpringLockConfigurationExtractor( + defaultLockAtMostForDuration(), defaultLockAtLeastForDuration(), resolver, durationConverter); } private Duration defaultLockAtLeastForDuration() { diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/LockingNotSupportedException.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/LockingNotSupportedException.java index f12f7f16b..f13e6b5b3 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/LockingNotSupportedException.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/LockingNotSupportedException.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/MethodProxyLockConfiguration.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/MethodProxyLockConfiguration.java index df188f2f3..b6f56017a 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/MethodProxyLockConfiguration.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/MethodProxyLockConfiguration.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; @@ -30,15 +28,10 @@ class MethodProxyLockConfiguration extends AbstractLockConfiguration { @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) MethodProxyScheduledLockAdvisor proxyScheduledLockAopBeanPostProcessor( - @Lazy LockProvider lockProvider, - @Lazy ExtendedLockConfigurationExtractor lockConfigurationExtractor - ) { + @Lazy LockProvider lockProvider, @Lazy ExtendedLockConfigurationExtractor lockConfigurationExtractor) { MethodProxyScheduledLockAdvisor advisor = new MethodProxyScheduledLockAdvisor( - lockConfigurationExtractor, - new DefaultLockingTaskExecutor(lockProvider) - ); + lockConfigurationExtractor, new DefaultLockingTaskExecutor(lockProvider)); advisor.setOrder(getOrder()); return advisor; - } } diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/MethodProxyScheduledLockAdvisor.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/MethodProxyScheduledLockAdvisor.java index e4ee8b4cf..bc3b48704 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/MethodProxyScheduledLockAdvisor.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/MethodProxyScheduledLockAdvisor.java @@ -1,20 +1,20 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; +import java.lang.annotation.Annotation; +import java.util.Optional; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockingTaskExecutor; import net.javacrumbs.shedlock.core.LockingTaskExecutor.TaskResult; @@ -29,29 +29,21 @@ import org.springframework.aop.support.ComposablePointcut; import org.springframework.aop.support.annotation.AnnotationMatchingPointcut; -import java.lang.annotation.Annotation; -import java.util.Optional; - class MethodProxyScheduledLockAdvisor extends AbstractPointcutAdvisor { private final Pointcut pointcut = new ComposablePointcut(methodPointcutFor(SchedulerLock.class)); private final Advice advice; - MethodProxyScheduledLockAdvisor(ExtendedLockConfigurationExtractor lockConfigurationExtractor, LockingTaskExecutor lockingTaskExecutor) { + MethodProxyScheduledLockAdvisor( + ExtendedLockConfigurationExtractor lockConfigurationExtractor, LockingTaskExecutor lockingTaskExecutor) { this.advice = new LockingInterceptor(lockConfigurationExtractor, lockingTaskExecutor); } - private static AnnotationMatchingPointcut methodPointcutFor(Class methodAnnotationType) { - return new AnnotationMatchingPointcut( - null, - methodAnnotationType, - true - ); - } + private static AnnotationMatchingPointcut methodPointcutFor(Class methodAnnotationType) { + return new AnnotationMatchingPointcut(null, methodAnnotationType, true); + } - /** - * Get the Pointcut that drives this advisor. - */ + /** Get the Pointcut that drives this advisor. */ @Override public Pointcut getPointcut() { return pointcut; @@ -66,7 +58,9 @@ private static class LockingInterceptor implements MethodInterceptor { private final ExtendedLockConfigurationExtractor lockConfigurationExtractor; private final LockingTaskExecutor lockingTaskExecutor; - LockingInterceptor(ExtendedLockConfigurationExtractor lockConfigurationExtractor, LockingTaskExecutor lockingTaskExecutor) { + LockingInterceptor( + ExtendedLockConfigurationExtractor lockConfigurationExtractor, + LockingTaskExecutor lockingTaskExecutor) { this.lockConfigurationExtractor = lockConfigurationExtractor; this.lockingTaskExecutor = lockingTaskExecutor; } @@ -79,7 +73,9 @@ public Object invoke(MethodInvocation invocation) throws Throwable { throw new LockingNotSupportedException("Can not lock method returning primitive value"); } - LockConfiguration lockConfiguration = lockConfigurationExtractor.getLockConfiguration(invocation.getThis(), invocation.getMethod(), invocation.getArguments()).get(); + LockConfiguration lockConfiguration = lockConfigurationExtractor + .getLockConfiguration(invocation.getThis(), invocation.getMethod(), invocation.getArguments()) + .get(); TaskResult result = lockingTaskExecutor.executeWithLock(invocation::proceed, lockConfiguration); if (Optional.class.equals(returnType)) { diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/RegisterDefaultTaskSchedulerPostProcessor.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/RegisterDefaultTaskSchedulerPostProcessor.java index 4f6304218..22781720f 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/RegisterDefaultTaskSchedulerPostProcessor.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/RegisterDefaultTaskSchedulerPostProcessor.java @@ -1,20 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; +import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; +import static org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.DEFAULT_TASK_SCHEDULER_BEAN_NAME; + +import java.util.concurrent.ScheduledExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; @@ -29,15 +31,9 @@ import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler; -import java.util.concurrent.ScheduledExecutorService; - -import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; -import static org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.DEFAULT_TASK_SCHEDULER_BEAN_NAME; - -/** - * Registers default TaskScheduler if none found. - */ -class RegisterDefaultTaskSchedulerPostProcessor implements BeanDefinitionRegistryPostProcessor, Ordered, BeanFactoryAware { +/** Registers default TaskScheduler if none found. */ +class RegisterDefaultTaskSchedulerPostProcessor + implements BeanDefinitionRegistryPostProcessor, Ordered, BeanFactoryAware { private BeanFactory beanFactory; private static final Logger logger = LoggerFactory.getLogger(RegisterDefaultTaskSchedulerPostProcessor.class); @@ -46,28 +42,31 @@ class RegisterDefaultTaskSchedulerPostProcessor implements BeanDefinitionRegistr public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { ListableBeanFactory listableBeanFactory = (ListableBeanFactory) this.beanFactory; if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(listableBeanFactory, TaskScheduler.class).length == 0) { - String[] scheduledExecutorsBeanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(listableBeanFactory, ScheduledExecutorService.class); + String[] scheduledExecutorsBeanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( + listableBeanFactory, ScheduledExecutorService.class); if (scheduledExecutorsBeanNames.length != 1) { logger.debug("Registering default TaskScheduler"); - registry.registerBeanDefinition(DEFAULT_TASK_SCHEDULER_BEAN_NAME, rootBeanDefinition(ConcurrentTaskScheduler.class).getBeanDefinition()); + registry.registerBeanDefinition( + DEFAULT_TASK_SCHEDULER_BEAN_NAME, + rootBeanDefinition(ConcurrentTaskScheduler.class).getBeanDefinition()); if (scheduledExecutorsBeanNames.length != 0) { logger.warn("Multiple ScheduledExecutorService found, do not know which one to use."); } } else { - logger.debug("Registering default TaskScheduler with existing ScheduledExecutorService {}", scheduledExecutorsBeanNames[0]); - registry.registerBeanDefinition(DEFAULT_TASK_SCHEDULER_BEAN_NAME, - rootBeanDefinition(ConcurrentTaskScheduler.class) - .addPropertyReference("scheduledExecutor", scheduledExecutorsBeanNames[0]) - .getBeanDefinition() - ); + logger.debug( + "Registering default TaskScheduler with existing ScheduledExecutorService {}", + scheduledExecutorsBeanNames[0]); + registry.registerBeanDefinition( + DEFAULT_TASK_SCHEDULER_BEAN_NAME, + rootBeanDefinition(ConcurrentTaskScheduler.class) + .addPropertyReference("scheduledExecutor", scheduledExecutorsBeanNames[0]) + .getBeanDefinition()); } } } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - - } + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {} @Override public int getOrder() { diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerLockConfigurationSelector.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerLockConfigurationSelector.java index 3de1be817..2544985d5 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerLockConfigurationSelector.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerLockConfigurationSelector.java @@ -1,43 +1,50 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; +import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode; +import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_METHOD; +import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_SCHEDULER; + import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; import org.springframework.context.annotation.AutoProxyRegistrar; import org.springframework.context.annotation.ImportSelector; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; -import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode; -import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_METHOD; -import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_SCHEDULER; - public class SchedulerLockConfigurationSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata metadata) { - AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(EnableSchedulerLock.class.getName(), false)); + AnnotationAttributes attributes = AnnotationAttributes.fromMap( + metadata.getAnnotationAttributes(EnableSchedulerLock.class.getName(), false)); InterceptMode mode = attributes.getEnum("interceptMode"); if (mode == PROXY_METHOD) { - return new String[]{AutoProxyRegistrar.class.getName(), LockConfigurationExtractorConfiguration.class.getName(), MethodProxyLockConfiguration.class.getName()}; + return new String[] { + AutoProxyRegistrar.class.getName(), + LockConfigurationExtractorConfiguration.class.getName(), + MethodProxyLockConfiguration.class.getName() + }; } else if (mode == PROXY_SCHEDULER) { - return new String[]{AutoProxyRegistrar.class.getName(), LockConfigurationExtractorConfiguration.class.getName(), SchedulerProxyLockConfiguration.class.getName(), RegisterDefaultTaskSchedulerPostProcessor.class.getName()}; + return new String[] { + AutoProxyRegistrar.class.getName(), + LockConfigurationExtractorConfiguration.class.getName(), + SchedulerProxyLockConfiguration.class.getName(), + RegisterDefaultTaskSchedulerPostProcessor.class.getName() + }; } else { throw new UnsupportedOperationException("Unknown mode " + mode); } - } } diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyLockConfiguration.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyLockConfiguration.java index c0c425d75..65d2074c7 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyLockConfiguration.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyLockConfiguration.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; @@ -30,10 +28,9 @@ class SchedulerProxyLockConfiguration extends AbstractLockConfiguration { @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) SchedulerProxyScheduledLockAdvisor proxyScheduledLockAopBeanPostProcessor( - @Lazy LockProvider lockProvider, - @Lazy ExtendedLockConfigurationExtractor lockConfigurationExtractor - ) { - SchedulerProxyScheduledLockAdvisor advisor = new SchedulerProxyScheduledLockAdvisor(new DefaultLockManager(lockProvider, lockConfigurationExtractor)); + @Lazy LockProvider lockProvider, @Lazy ExtendedLockConfigurationExtractor lockConfigurationExtractor) { + SchedulerProxyScheduledLockAdvisor advisor = new SchedulerProxyScheduledLockAdvisor( + new DefaultLockManager(lockProvider, lockConfigurationExtractor)); advisor.setOrder(getOrder()); return advisor; } diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyScheduledLockAdvisor.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyScheduledLockAdvisor.java index 35a63bbbf..b1595651b 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyScheduledLockAdvisor.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyScheduledLockAdvisor.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; @@ -39,9 +37,7 @@ class SchedulerProxyScheduledLockAdvisor extends AbstractPointcutAdvisor { this.advice = new LockingInterceptor(lockManager); } - /** - * Get the Pointcut that drives this advisor. - */ + /** Get the Pointcut that drives this advisor. */ @Override public Pointcut getPointcut() { return pointcut; @@ -59,7 +55,6 @@ private LockingInterceptor(LockManager lockManager) { this.lockManager = lockManager; } - @Override public Object invoke(MethodInvocation invocation) throws Throwable { Object[] arguments = invocation.getArguments(); diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SpringLockConfigurationExtractor.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SpringLockConfigurationExtractor.java index 82f523e0c..603b4401c 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SpringLockConfigurationExtractor.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/SpringLockConfigurationExtractor.java @@ -1,20 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; +import static java.time.temporal.ChronoUnit.MILLIS; +import static java.util.Objects.requireNonNull; + +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.time.Duration; +import java.util.Optional; import net.javacrumbs.shedlock.core.ClockProvider; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.spring.ExtendedLockConfigurationExtractor; @@ -35,41 +40,34 @@ import org.springframework.util.StringUtils; import org.springframework.util.StringValueResolver; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; -import java.time.Duration; -import java.util.Optional; - -import static java.time.temporal.ChronoUnit.MILLIS; -import static java.util.Objects.requireNonNull; - class SpringLockConfigurationExtractor implements ExtendedLockConfigurationExtractor { private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser(); private static final ParserContext PARSER_CONTEXT = new TemplateParserContext(); private final Duration defaultLockAtMostFor; private final Duration defaultLockAtLeastFor; + @Nullable private final StringValueResolver embeddedValueResolver; + private final Converter durationConverter; private final Logger logger = LoggerFactory.getLogger(SpringLockConfigurationExtractor.class); public SpringLockConfigurationExtractor( - Duration defaultLockAtMostFor, - Duration defaultLockAtLeastFor, - @Nullable StringValueResolver embeddedValueResolver, - Converter durationConverter - ) { + Duration defaultLockAtMostFor, + Duration defaultLockAtLeastFor, + @Nullable StringValueResolver embeddedValueResolver, + Converter durationConverter) { this.defaultLockAtMostFor = requireNonNull(defaultLockAtMostFor); this.defaultLockAtLeastFor = requireNonNull(defaultLockAtLeastFor); this.durationConverter = requireNonNull(durationConverter); this.embeddedValueResolver = embeddedValueResolver; } - @Override public Optional getLockConfiguration(Runnable task) { if (task instanceof ScheduledMethodRunnable scheduledMethodRunnable) { - return getLockConfiguration(scheduledMethodRunnable.getTarget(), scheduledMethodRunnable.getMethod(), new Object[] {}); + return getLockConfiguration( + scheduledMethodRunnable.getTarget(), scheduledMethodRunnable.getMethod(), new Object[] {}); } else { logger.debug("Unknown task type " + task); } @@ -88,10 +86,10 @@ public Optional getLockConfiguration(Object target, Method me private LockConfiguration getLockConfiguration(AnnotationData annotation, Method method, Object[] parameterValues) { return new LockConfiguration( - ClockProvider.now(), - getName(annotation, method, parameterValues), - getLockAtMostFor(annotation), - getLockAtLeastFor(annotation)); + ClockProvider.now(), + getName(annotation, method, parameterValues), + getLockAtMostFor(annotation), + getLockAtLeastFor(annotation)); } private String getName(AnnotationData annotation, Method method, Object[] parameterValues) { @@ -105,14 +103,18 @@ private String getName(AnnotationData annotation, Method method, Object[] parame private String parseSpEL(String name, Method method, Object[] parameterValues) { return getEvaluationContext(method, parameterValues) - .map(evaluationContext -> EXPRESSION_PARSER.parseExpression(name, PARSER_CONTEXT).getValue(evaluationContext, String.class)) - .orElse(name); + .map(evaluationContext -> EXPRESSION_PARSER + .parseExpression(name, PARSER_CONTEXT) + .getValue(evaluationContext, String.class)) + .orElse(name); } private Optional getEvaluationContext(Method method, Object[] parameterValues) { if (method.getParameters().length > 0 && method.getParameters().length == parameterValues.length) { Parameter[] parameters = method.getParameters(); - EvaluationContext evaluationContext = SimpleEvaluationContext.forReadOnlyDataBinding().withInstanceMethods().build(); + EvaluationContext evaluationContext = SimpleEvaluationContext.forReadOnlyDataBinding() + .withInstanceMethods() + .build(); for (int i = 0; i < parameters.length; i++) { evaluationContext.setVariable(parameters[i].getName(), parameterValues[i]); } @@ -124,23 +126,22 @@ private Optional getEvaluationContext(Method method, Object[] Duration getLockAtMostFor(AnnotationData annotation) { return getValue( - annotation.getLockAtMostFor(), - annotation.getLockAtMostForString(), - this.defaultLockAtMostFor, - "lockAtMostForString" - ); + annotation.getLockAtMostFor(), + annotation.getLockAtMostForString(), + this.defaultLockAtMostFor, + "lockAtMostForString"); } Duration getLockAtLeastFor(AnnotationData annotation) { return getValue( - annotation.getLockAtLeastFor(), - annotation.getLockAtLeastForString(), - this.defaultLockAtLeastFor, - "lockAtLeastForString" - ); + annotation.getLockAtLeastFor(), + annotation.getLockAtLeastForString(), + this.defaultLockAtLeastFor, + "lockAtLeastForString"); } - private Duration getValue(long valueFromAnnotation, String stringValueFromAnnotation, Duration defaultValue, final String paramName) { + private Duration getValue( + long valueFromAnnotation, String stringValueFromAnnotation, Duration defaultValue, final String paramName) { if (valueFromAnnotation >= 0) { return Duration.of(valueFromAnnotation, MILLIS); } else if (StringUtils.hasText(stringValueFromAnnotation)) { @@ -150,11 +151,13 @@ private Duration getValue(long valueFromAnnotation, String stringValueFromAnnota try { Duration result = durationConverter.convert(stringValueFromAnnotation); if (result.isNegative()) { - throw new IllegalArgumentException("Invalid " + paramName + " value \"" + stringValueFromAnnotation + "\" - cannot set negative duration"); + throw new IllegalArgumentException("Invalid " + paramName + " value \"" + stringValueFromAnnotation + + "\" - cannot set negative duration"); } return result; } catch (IllegalStateException nfe) { - throw new IllegalArgumentException("Invalid " + paramName + " value \"" + stringValueFromAnnotation + "\" - cannot parse into long nor duration"); + throw new IllegalArgumentException("Invalid " + paramName + " value \"" + stringValueFromAnnotation + + "\" - cannot parse into long nor duration"); } } else { return defaultValue; @@ -170,8 +173,7 @@ AnnotationData findAnnotation(Object target, Method method) { // Try to find annotation on proxied class Class targetClass = AopUtils.getTargetClass(target); try { - Method methodOnTarget = targetClass - .getMethod(method.getName(), method.getParameterTypes()); + Method methodOnTarget = targetClass.getMethod(method.getName(), method.getParameterTypes()); return findAnnotation(methodOnTarget); } catch (NoSuchMethodException e) { return null; @@ -183,7 +185,8 @@ AnnotationData findAnnotation(Object target, Method method) { private AnnotationData findAnnotation(Method method) { SchedulerLock annotation = AnnotatedElementUtils.getMergedAnnotation(method, SchedulerLock.class); if (annotation != null) { - return new AnnotationData(annotation.name(), -1, annotation.lockAtMostFor(), -1, annotation.lockAtLeastFor()); + return new AnnotationData( + annotation.name(), -1, annotation.lockAtMostFor(), -1, annotation.lockAtLeastFor()); } return null; } @@ -199,7 +202,12 @@ static class AnnotationData { private final long lockAtLeastFor; private final String lockAtLeastForString; - private AnnotationData(String name, long lockAtMostFor, String lockAtMostForString, long lockAtLeastFor, String lockAtLeastForString) { + private AnnotationData( + String name, + long lockAtMostFor, + String lockAtMostForString, + long lockAtLeastFor, + String lockAtLeastForString) { this.name = name; this.lockAtMostFor = lockAtMostFor; this.lockAtMostForString = lockAtMostForString; @@ -228,5 +236,3 @@ public String getLockAtLeastForString() { } } } - - diff --git a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/StringToDurationConverter.java b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/StringToDurationConverter.java index 2e0376164..7d4559176 100644 --- a/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/StringToDurationConverter.java +++ b/spring/shedlock-spring/src/main/java/net/javacrumbs/shedlock/spring/aop/StringToDurationConverter.java @@ -1,21 +1,18 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; - /* * Copyright 2012-2017 the original author or authors. * @@ -32,9 +29,6 @@ * limitations under the License. */ -import org.springframework.core.convert.converter.Converter; -import org.springframework.util.Assert; - import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Collections; @@ -42,14 +36,17 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.springframework.core.convert.converter.Converter; +import org.springframework.util.Assert; /** * {@link Converter} for {@link String} to {@link Duration}. Support - * {@link Duration#parse(CharSequence)} as well a more readable {@code 10s} form. + * {@link Duration#parse(CharSequence)} as well a more readable {@code 10s} + * form. * * @author Phillip Webb - *

- * Copied from org.springframework.boot.context.properties.bind.convert + *

+ * Copied from org.springframework.boot.context.properties.bind.convert */ class StringToDurationConverter implements Converter { @@ -96,4 +93,3 @@ private ChronoUnit getUnit(String value) { return unit; } } - diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/TestUtils.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/TestUtils.java index 572ef4fa4..67395d6d5 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/TestUtils.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/TestUtils.java @@ -1,30 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static org.mockito.ArgumentMatchers.argThat; + +import java.time.Instant; import net.javacrumbs.shedlock.core.LockConfiguration; import org.mockito.ArgumentMatcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Instant; - -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static org.mockito.ArgumentMatchers.argThat; - public class TestUtils { private static final int GAP = 1000; @@ -36,14 +33,15 @@ public static LockConfiguration hasParams(String name, long lockAtMostFor, long @Override public boolean matches(LockConfiguration c) { return name.equals(c.getName()) - && isNearTo(lockAtMostFor, c.getLockAtMostUntil()) - && isNearTo(lockAtLeastFor, c.getLockAtLeastUntil()); + && isNearTo(lockAtMostFor, c.getLockAtMostUntil()) + && isNearTo(lockAtLeastFor, c.getLockAtLeastUntil()); } @Override public String toString() { Instant now = now(); - return "hasParams(\"" + name + "\", " + now.plusMillis(lockAtMostFor) + ", " + now.plusMillis(lockAtLeastFor) + ")"; + return "hasParams(\"" + name + "\", " + now.plusMillis(lockAtMostFor) + ", " + + now.plusMillis(lockAtLeastFor) + ")"; } }); } diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AbstractSchedulerProxyTest.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AbstractSchedulerProxyTest.java index 00f4cc74c..f97b8b529 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AbstractSchedulerProxyTest.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AbstractSchedulerProxyTest.java @@ -1,20 +1,30 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static net.javacrumbs.shedlock.spring.TestUtils.hasParams; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.concurrent.ExecutionException; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.SimpleLock; import net.javacrumbs.shedlock.spring.ExtendedLockConfigurationExtractor; @@ -30,20 +40,6 @@ import org.springframework.scheduling.support.ScheduledMethodRunnable; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.Optional; -import java.util.concurrent.ExecutionException; - -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static net.javacrumbs.shedlock.spring.TestUtils.hasParams; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - - @ExtendWith(SpringExtension.class) public abstract class AbstractSchedulerProxyTest { @Autowired @@ -64,13 +60,13 @@ public abstract class AbstractSchedulerProxyTest { public void prepareMocks() { Mockito.reset(lockProvider, simpleLock); when(lockProvider.lock(any())).thenReturn(Optional.of(simpleLock)); - } protected abstract void assertRightSchedulerUsed(); @Test - public void shouldCallLockProviderOnSchedulerCall() throws NoSuchMethodException, ExecutionException, InterruptedException { + public void shouldCallLockProviderOnSchedulerCall() + throws NoSuchMethodException, ExecutionException, InterruptedException { Runnable task = task("annotatedMethod"); taskScheduler.schedule(task, now()).get(); verify(lockProvider).lock(hasParams("lockName", 30_000, getDefaultLockAtLeastFor())); @@ -85,7 +81,6 @@ public void shouldUseCustomAnnotation() throws NoSuchMethodException, ExecutionE verify(simpleLock).unlock(); } - @Test public void shouldUserPropertyName() throws NoSuchMethodException, ExecutionException, InterruptedException { Runnable task = task("spelMethod"); @@ -106,7 +101,7 @@ public void shouldRethrowRuntimeException() throws NoSuchMethodException { public void shouldNotLockTaskExecutorMethods() { assertThat(taskScheduler).isInstanceOf(TaskExecutor.class); - ((TaskExecutor)taskScheduler).execute(() -> {}); + ((TaskExecutor) taskScheduler).execute(() -> {}); verifyNoInteractions(lockProvider); } @@ -114,7 +109,6 @@ private long getDefaultLockAtLeastFor() { return StringToDurationConverter.INSTANCE.convert(defaultLockAtLeastFor).toMillis(); } - private void schedule(Runnable task) throws InterruptedException, ExecutionException { taskScheduler.schedule(task, now()).get(); } @@ -125,7 +119,7 @@ private ScheduledMethodRunnable task(String methodName) throws NoSuchMethodExcep @Test public void shouldNotLockProviderOnPureRunnable() throws ExecutionException, InterruptedException { - taskScheduler.schedule(() -> { }, now()).get(); + taskScheduler.schedule(() -> {}, now()).get(); verifyNoInteractions(lockProvider); } @@ -145,13 +139,10 @@ public void custom() { } @SchedulerLock(name = "${property.value}", lockAtMostFor = "1000", lockAtLeastFor = "500") - public void spelMethod() { - - } + public void spelMethod() {} @SchedulerLock(name = "exception", lockAtMostFor = "1500") public void throwsException() { throw new NullPointerException("Just for test"); } - } diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AbstractSpringLockConfigurationExtractorTest.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AbstractSpringLockConfigurationExtractorTest.java index 4056c0389..7375d696e 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AbstractSpringLockConfigurationExtractorTest.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AbstractSpringLockConfigurationExtractorTest.java @@ -1,22 +1,32 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; -import java.lang.reflect.Method; +import static java.time.temporal.ChronoUnit.MILLIS; +import static java.time.temporal.ChronoUnit.SECONDS; +import static net.javacrumbs.shedlock.core.ClockProvider.now; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import java.lang.reflect.Method; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.time.temporal.TemporalAmount; +import java.util.Optional; import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.spring.aop.SpringLockConfigurationExtractor.AnnotationData; import net.javacrumbs.shedlock.spring.proxytest.BeanInterface; @@ -27,26 +37,12 @@ import org.springframework.scheduling.support.ScheduledMethodRunnable; import org.springframework.util.StringValueResolver; -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import java.time.temporal.TemporalAmount; -import java.util.Optional; - -import static java.time.temporal.ChronoUnit.MILLIS; -import static java.time.temporal.ChronoUnit.SECONDS; -import static net.javacrumbs.shedlock.core.ClockProvider.now; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public abstract class AbstractSpringLockConfigurationExtractorTest { private static final Duration DEFAULT_LOCK_TIME = Duration.of(30, ChronoUnit.MINUTES); private static final Duration DEFAULT_LOCK_AT_LEAST_FOR = Duration.of(5, ChronoUnit.MILLIS); private final StringValueResolver embeddedValueResolver = mock(StringValueResolver.class); - private final SpringLockConfigurationExtractor extractor = new SpringLockConfigurationExtractor(DEFAULT_LOCK_TIME, DEFAULT_LOCK_AT_LEAST_FOR, embeddedValueResolver, new StringToDurationConverter()); - + private final SpringLockConfigurationExtractor extractor = new SpringLockConfigurationExtractor( + DEFAULT_LOCK_TIME, DEFAULT_LOCK_AT_LEAST_FOR, embeddedValueResolver, new StringToDurationConverter()); @Test public void shouldLockForDefaultTimeIfNoAnnotation() throws NoSuchMethodException { @@ -141,25 +137,31 @@ public void shouldGetNameAndLockTimeFromAnnotation() throws NoSuchMethodExceptio mockResolvedValue("lockName", "lockName"); mockResolvedValue("100", "100"); ScheduledMethodRunnable runnable = new ScheduledMethodRunnable(this, "annotatedMethod"); - LockConfiguration lockConfiguration = extractor.getLockConfiguration(runnable).get(); + LockConfiguration lockConfiguration = + extractor.getLockConfiguration(runnable).get(); assertThat(lockConfiguration.getName()).isEqualTo("lockName"); assertThat(lockConfiguration.getLockAtMostUntil()).isBeforeOrEqualTo(now().plus(100, MILLIS)); - assertThat(lockConfiguration.getLockAtLeastUntil()).isAfter(now().plus(DEFAULT_LOCK_AT_LEAST_FOR).minus(1, SECONDS)); + assertThat(lockConfiguration.getLockAtLeastUntil()) + .isAfter(now().plus(DEFAULT_LOCK_AT_LEAST_FOR).minus(1, SECONDS)); } @Test public void shouldGetNameFromSpringVariable() throws NoSuchMethodException { mockResolvedValue("${name}", "lockNameX"); ScheduledMethodRunnable runnable = new ScheduledMethodRunnable(this, "annotatedMethodWithNameVariable"); - LockConfiguration lockConfiguration = extractor.getLockConfiguration(runnable).get(); + LockConfiguration lockConfiguration = + extractor.getLockConfiguration(runnable).get(); assertThat(lockConfiguration.getName()).isEqualTo("lockNameX"); } @Test public void shouldGetNameFromSpringExpression() throws NoSuchMethodException { mockResolvedValue("lockName-value-1-3-5", "lockName-value-1-3-5"); - Method method = this.getClass().getMethod("annotatedMethodWithNameSpringExpression", String.class, Integer.class); - LockConfiguration lockConfiguration = extractor.getLockConfiguration(this, method, new Object[] {"value", 1}).get(); + Method method = + this.getClass().getMethod("annotatedMethodWithNameSpringExpression", String.class, Integer.class); + LockConfiguration lockConfiguration = extractor + .getLockConfiguration(this, method, new Object[] {"value", 1}) + .get(); assertThat(lockConfiguration.getName()).isEqualTo("lockName-value-1-3-5"); } @@ -167,7 +169,9 @@ public void shouldGetNameFromSpringExpression() throws NoSuchMethodException { public void shouldGetNameFromSpringExpressionAndSpringVariable() throws NoSuchMethodException { mockResolvedValue("${name}-value", "lockName-value"); Method method = this.getClass().getMethod("annotatedMethodWithNameSpringExpressionAndVariable", String.class); - LockConfiguration lockConfiguration = extractor.getLockConfiguration(this, method, new Object[] {"value"}).get(); + LockConfiguration lockConfiguration = extractor + .getLockConfiguration(this, method, new Object[] {"value"}) + .get(); assertThat(lockConfiguration.getName()).isEqualTo("lockName-value"); } @@ -182,7 +186,8 @@ private void noopResolver() { private void doTestFindAnnotationOnProxy(Class config) throws NoSuchMethodException { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(config)) { BeanInterface bean = context.getBean(BeanInterface.class); - assertThat(extractor.findAnnotation(bean, bean.getClass().getMethod("method"))).isNotNull(); + assertThat(extractor.findAnnotation(bean, bean.getClass().getMethod("method"))) + .isNotNull(); } } diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AopCleanupTest.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AopCleanupTest.java index 08bd96417..1c1e4fb10 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AopCleanupTest.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AopCleanupTest.java @@ -1,20 +1,21 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; @@ -25,9 +26,6 @@ import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - public class AopCleanupTest { @Test public void shouldCloseTaskExecutor() { @@ -37,7 +35,6 @@ public void shouldCloseTaskExecutor() { assertThat(context.isActive()).isFalse(); } - @Configuration @EnableScheduling @EnableSchedulerLock(defaultLockAtMostFor = "PT30S") @@ -51,8 +48,6 @@ public LockProvider lockProvider() { @Scheduled(fixedRate = 10_000) @SchedulerLock(name = "task") - public void task() { - - } + public void task() {} } } diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AopOrderingTest.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AopOrderingTest.java index 4ffe18cb7..2c68a0167 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AopOrderingTest.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/AopOrderingTest.java @@ -1,20 +1,29 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.beans.factory.config.BeanDefinition.ROLE_INFRASTRUCTURE; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; import net.javacrumbs.shedlock.core.LockAssert; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.SimpleLock; @@ -35,19 +44,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.springframework.beans.factory.config.BeanDefinition.ROLE_INFRASTRUCTURE; - - @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = {AopOrderingTest.AopOrderConfig.class, AopOrderingTest.Aspects.class}) public class AopOrderingTest { @@ -88,7 +84,6 @@ public LockProvider lockProvider() { public TestBean testBean() { return new TestBean(); } - } @Configuration @@ -96,14 +91,12 @@ static class Aspects { @Bean @Role(ROLE_INFRASTRUCTURE) public Advisor firstAspect() { - DefaultPointcutAdvisor aspect = new DefaultPointcutAdvisor( - shedlockPointcut(), - (MethodInterceptor) invocation -> { - aspectsCalled.add("first"); - assertThatThrownBy(LockAssert::assertLocked).isInstanceOf(IllegalStateException.class); - return invocation.proceed(); - } - ); + DefaultPointcutAdvisor aspect = + new DefaultPointcutAdvisor(shedlockPointcut(), (MethodInterceptor) invocation -> { + aspectsCalled.add("first"); + assertThatThrownBy(LockAssert::assertLocked).isInstanceOf(IllegalStateException.class); + return invocation.proceed(); + }); aspect.setOrder(0); return aspect; } @@ -111,26 +104,19 @@ public Advisor firstAspect() { @Bean @Role(ROLE_INFRASTRUCTURE) public Advisor lastAspect() { - DefaultPointcutAdvisor aspect = new DefaultPointcutAdvisor( - shedlockPointcut(), - (MethodInterceptor) invocation -> { - aspectsCalled.add("last"); - LockAssert.assertLocked(); - return invocation.proceed(); - } - ); + DefaultPointcutAdvisor aspect = + new DefaultPointcutAdvisor(shedlockPointcut(), (MethodInterceptor) invocation -> { + aspectsCalled.add("last"); + LockAssert.assertLocked(); + return invocation.proceed(); + }); aspect.setOrder(200); return aspect; } private static AnnotationMatchingPointcut shedlockPointcut() { - return new AnnotationMatchingPointcut( - null, - SchedulerLock.class, - true - ); + return new AnnotationMatchingPointcut(null, SchedulerLock.class, true); } - } static class TestBean { diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/MethodProxyAopConfig.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/MethodProxyAopConfig.java index bb4117542..e73909cdf 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/MethodProxyAopConfig.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/MethodProxyAopConfig.java @@ -1,21 +1,24 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; +import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; +import static org.mockito.Mockito.mock; +import java.io.IOException; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; @@ -24,16 +27,11 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.scheduling.annotation.EnableScheduling; -import java.io.IOException; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; - -import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; -import static org.mockito.Mockito.mock; - @Configuration @EnableScheduling -@EnableSchedulerLock(defaultLockAtMostFor = "${default.lock_at_most_for}", defaultLockAtLeastFor = "${default.lock_at_least_for}") +@EnableSchedulerLock( + defaultLockAtMostFor = "${default.lock_at_most_for}", + defaultLockAtLeastFor = "${default.lock_at_least_for}") @PropertySource("test.properties") public class MethodProxyAopConfig { @@ -131,8 +129,6 @@ static class AnotherTestBeanImpl implements AnotherTestBean { @Override @SchedulerLock(name = "classAnnotation") - public void runManually() { - - } + public void runManually() {} } } diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/MethodProxyAopTest.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/MethodProxyAopTest.java index 96e6b7217..2dbab3ebf 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/MethodProxyAopTest.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/MethodProxyAopTest.java @@ -1,20 +1,29 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; +import static net.javacrumbs.shedlock.spring.TestUtils.hasParams; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.Optional; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.SimpleLock; import net.javacrumbs.shedlock.spring.ExtendedLockConfigurationExtractor; @@ -28,19 +37,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.io.IOException; -import java.util.Optional; - -import static net.javacrumbs.shedlock.spring.TestUtils.hasParams; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - - @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = MethodProxyAopConfig.class) public class MethodProxyAopTest { @@ -103,7 +99,6 @@ public void shouldRethrowDeclaredException() { assertThat(testBean.wasMethodCalled()).isTrue(); } - @Test public void shouldFailOnPrimitiveReturnType() { assertThatThrownBy(() -> testBean.returnsValue()).isInstanceOf(LockingNotSupportedException.class); diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/MyScheduled.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/MyScheduled.java index 967c1b052..736a77a24 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/MyScheduled.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/MyScheduled.java @@ -1,29 +1,26 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; -import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; -import org.springframework.core.annotation.AliasFor; -import org.springframework.scheduling.annotation.Async; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; +import org.springframework.core.annotation.AliasFor; +import org.springframework.scheduling.annotation.Async; @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyCglibTest.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyCglibTest.java index ee1f7e4ee..083a6dc0f 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyCglibTest.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyCglibTest.java @@ -1,20 +1,23 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; +import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_SCHEDULER; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import java.util.concurrent.Executors; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; import org.junit.jupiter.api.Test; @@ -29,13 +32,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.concurrent.Executors; - -import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_SCHEDULER; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - - @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = SchedulerProxyCglibTest.SchedulerWrapperConfig.class) public class SchedulerProxyCglibTest extends AbstractSchedulerProxyTest { @@ -52,7 +48,11 @@ protected void assertRightSchedulerUsed() { @Configuration @EnableScheduling - @EnableSchedulerLock(defaultLockAtMostFor = "${default.lock_at_most_for}", defaultLockAtLeastFor = "${default.lock_at_least_for}", proxyTargetClass = true, interceptMode = PROXY_SCHEDULER) + @EnableSchedulerLock( + defaultLockAtMostFor = "${default.lock_at_most_for}", + defaultLockAtLeastFor = "${default.lock_at_least_for}", + proxyTargetClass = true, + interceptMode = PROXY_SCHEDULER) @PropertySource("test.properties") static class SchedulerWrapperConfig { @@ -61,15 +61,13 @@ public LockProvider lockProvider() { return mock(LockProvider.class); } - @Bean public TaskScheduler taskScheduler() { return new MyTaskScheduler(); } } - interface MyInterface { - } + interface MyInterface {} private static class MyTaskScheduler extends ConcurrentTaskScheduler implements MyInterface { MyTaskScheduler() { diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyDefaultSchedulerTest.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyDefaultSchedulerTest.java index 5af4680cd..19aff6778 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyDefaultSchedulerTest.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyDefaultSchedulerTest.java @@ -1,20 +1,23 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; +import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_SCHEDULER; +import static org.mockito.Mockito.mock; + +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; import org.junit.jupiter.api.extension.ExtendWith; @@ -26,28 +29,20 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; - -import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_SCHEDULER; -import static org.mockito.Mockito.mock; - - -/** - * Test creation of default task scheduler - */ +/** Test creation of default task scheduler */ @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = SchedulerProxyDefaultSchedulerTest.SchedulerWrapperConfig.class) public class SchedulerProxyDefaultSchedulerTest extends AbstractSchedulerProxyTest { @Override - protected void assertRightSchedulerUsed() { - - } + protected void assertRightSchedulerUsed() {} @Configuration @EnableScheduling - @EnableSchedulerLock(defaultLockAtMostFor = "${default.lock_at_most_for}", defaultLockAtLeastFor = "${default.lock_at_least_for}", interceptMode = PROXY_SCHEDULER) + @EnableSchedulerLock( + defaultLockAtMostFor = "${default.lock_at_most_for}", + defaultLockAtLeastFor = "${default.lock_at_least_for}", + interceptMode = PROXY_SCHEDULER) @PropertySource("test.properties") static class SchedulerWrapperConfig { diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyScheduledExecutorServiceSchedulerTest.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyScheduledExecutorServiceSchedulerTest.java index 0ce5444ca..01e5c1b52 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyScheduledExecutorServiceSchedulerTest.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyScheduledExecutorServiceSchedulerTest.java @@ -1,20 +1,24 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; +import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_SCHEDULER; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; import org.junit.jupiter.api.extension.ExtendWith; @@ -26,17 +30,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; - -import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_SCHEDULER; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - - -/** - * Test creation of default task scheduler - */ +/** Test creation of default task scheduler */ @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = SchedulerProxyScheduledExecutorServiceSchedulerTest.SchedulerWrapperConfig.class) public class SchedulerProxyScheduledExecutorServiceSchedulerTest extends AbstractSchedulerProxyTest { @@ -47,7 +41,10 @@ protected void assertRightSchedulerUsed() { @Configuration @EnableScheduling - @EnableSchedulerLock(defaultLockAtMostFor = "${default.lock_at_most_for}", defaultLockAtLeastFor = "${default.lock_at_least_for}", interceptMode = PROXY_SCHEDULER) + @EnableSchedulerLock( + defaultLockAtMostFor = "${default.lock_at_most_for}", + defaultLockAtLeastFor = "${default.lock_at_least_for}", + interceptMode = PROXY_SCHEDULER) @PropertySource("test.properties") static class SchedulerWrapperConfig { diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyTest.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyTest.java index 9502e5d01..c3ef3cfb3 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyTest.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SchedulerProxyTest.java @@ -1,20 +1,23 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; +import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_SCHEDULER; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import java.util.concurrent.Executors; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; import org.junit.jupiter.api.Test; @@ -29,13 +32,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.concurrent.Executors; - -import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_SCHEDULER; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - - @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = SchedulerProxyTest.SchedulerWrapperConfig.class) public class SchedulerProxyTest extends AbstractSchedulerProxyTest { @@ -53,7 +49,10 @@ protected void assertRightSchedulerUsed() { @Configuration @EnableScheduling - @EnableSchedulerLock(defaultLockAtMostFor = "${default.lock_at_most_for}", defaultLockAtLeastFor = "${default.lock_at_least_for}", interceptMode = PROXY_SCHEDULER) + @EnableSchedulerLock( + defaultLockAtMostFor = "${default.lock_at_most_for}", + defaultLockAtLeastFor = "${default.lock_at_least_for}", + interceptMode = PROXY_SCHEDULER) @PropertySource("test.properties") static class SchedulerWrapperConfig { @@ -62,7 +61,6 @@ public LockProvider lockProvider() { return mock(LockProvider.class); } - @Bean public TaskScheduler taskScheduler() { return new MyTaskScheduler(); diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SpringLockConfigurationExtractorTest.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SpringLockConfigurationExtractorTest.java index 3bda00acc..a780c1e37 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SpringLockConfigurationExtractorTest.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/SpringLockConfigurationExtractorTest.java @@ -1,96 +1,67 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; -import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; -import org.springframework.core.annotation.AliasFor; -import org.springframework.scheduling.annotation.Scheduled; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; +import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; +import org.springframework.core.annotation.AliasFor; +import org.springframework.scheduling.annotation.Scheduled; public class SpringLockConfigurationExtractorTest extends AbstractSpringLockConfigurationExtractorTest { @SchedulerLock(name = "lockName", lockAtMostFor = "100") - public void annotatedMethod() { - - } + public void annotatedMethod() {} @SchedulerLock(name = "lockName", lockAtMostFor = "${placeholder}") - public void annotatedMethodWithString() { - - } + public void annotatedMethodWithString() {} @SchedulerLock(name = "lockName", lockAtMostFor = "PT1S") - public void annotatedMethodWithDurationString() { - - } + public void annotatedMethodWithDurationString() {} @SchedulerLock(name = "${name}") - public void annotatedMethodWithNameVariable() { - - } + public void annotatedMethodWithNameVariable() {} @SchedulerLock(name = "lockName-#{#arg0 + '-' + #arg1 + '-' + (1 + 2) + '-' + 'abcde'.length()}") - public void annotatedMethodWithNameSpringExpression(String arg0, Integer arg1) { - - } + public void annotatedMethodWithNameSpringExpression(String arg0, Integer arg1) {} @SchedulerLock(name = "${name}-#{#arg0}") - public void annotatedMethodWithNameSpringExpressionAndVariable(String arg0) { - - } + public void annotatedMethodWithNameSpringExpressionAndVariable(String arg0) {} @SchedulerLock(name = "lockName") - public void annotatedMethodWithoutLockAtMostFor() { - - } + public void annotatedMethodWithoutLockAtMostFor() {} @SchedulerLock(name = "lockName", lockAtLeastFor = "0") - public void annotatedMethodWithZeroGracePeriod() { - - } + public void annotatedMethodWithZeroGracePeriod() {} @SchedulerLock(name = "lockName", lockAtLeastFor = "10") - public void annotatedMethodWithPositiveGracePeriod() { - - } + public void annotatedMethodWithPositiveGracePeriod() {} @SchedulerLock(name = "lockName", lockAtLeastFor = "10ms") - public void annotatedMethodWithPositiveGracePeriodWithString() { - - } + public void annotatedMethodWithPositiveGracePeriodWithString() {} @SchedulerLock(name = "lockName", lockAtLeastFor = "-1s") - public void annotatedMethodWithNegativeGracePeriod() { - - } + public void annotatedMethodWithNegativeGracePeriod() {} @ScheduledLocked(name = "lockName1") - public void composedAnnotation() { + public void composedAnnotation() {} - } - - public void methodWithoutAnnotation() { - - } + public void methodWithoutAnnotation() {} @Target(METHOD) @Retention(RUNTIME) diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/StringToDurationConverterTest.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/StringToDurationConverterTest.java index 8e0462c34..d22365c41 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/StringToDurationConverterTest.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/aop/StringToDurationConverterTest.java @@ -1,27 +1,24 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.aop; -import org.junit.jupiter.api.Test; - -import java.time.Duration; - import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import java.time.Duration; +import org.junit.jupiter.api.Test; + /** * Tests for {@link StringToDurationConverter}. * @@ -106,12 +103,12 @@ public void convertWhenSimpleWithoutSuffixShouldReturnDuration() { @Test public void convertWhenBadFormatShouldThrowException() { - assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> convert("10foo")) - .withMessageContaining("'10foo' is not a valid duration"); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> convert("10foo")) + .withMessageContaining("'10foo' is not a valid duration"); } private Duration convert(String source) { return new StringToDurationConverter().convert(source); } - } diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/AbstractSchedulerConfig.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/AbstractSchedulerConfig.java index d9c0d7b4e..25182d6fd 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/AbstractSchedulerConfig.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/AbstractSchedulerConfig.java @@ -1,21 +1,23 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.it; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import java.util.Optional; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.core.SimpleLock; import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; @@ -24,12 +26,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.Scheduled; -import java.util.Optional; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public abstract class AbstractSchedulerConfig { private static final Logger logger = LoggerFactory.getLogger(ProxyIntegrationTest.class); diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/AbstractSchedulerTest.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/AbstractSchedulerTest.java index 7d43977b4..f43e36d05 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/AbstractSchedulerTest.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/AbstractSchedulerTest.java @@ -1,31 +1,28 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.it; -import net.javacrumbs.shedlock.core.LockProvider; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.junit.jupiter.SpringExtension; - import static net.javacrumbs.shedlock.spring.TestUtils.hasParams; import static org.awaitility.Awaitility.await; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; +import net.javacrumbs.shedlock.core.LockProvider; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) public abstract class AbstractSchedulerTest { diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/ProxyIntegrationTest.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/ProxyIntegrationTest.java index 3fa5c8ba8..c8d687a45 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/ProxyIntegrationTest.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/ProxyIntegrationTest.java @@ -1,34 +1,30 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.it; +import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_METHOD; + import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.test.context.ContextConfiguration; -import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_METHOD; - - @ContextConfiguration(classes = ProxyIntegrationTest.AopSchedulerConfig.class) public class ProxyIntegrationTest extends AbstractSchedulerTest { @Configuration @EnableScheduling @EnableSchedulerLock(interceptMode = PROXY_METHOD, defaultLockAtMostFor = "PT30S") - public static class AopSchedulerConfig extends AbstractSchedulerConfig { - } + public static class AopSchedulerConfig extends AbstractSchedulerConfig {} } diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/SchedulerIntegrationTest.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/SchedulerIntegrationTest.java index 111db23b0..30fd9e606 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/SchedulerIntegrationTest.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/it/SchedulerIntegrationTest.java @@ -1,34 +1,30 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.it; +import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_SCHEDULER; + import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.test.context.ContextConfiguration; -import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_SCHEDULER; - - @ContextConfiguration(classes = SchedulerIntegrationTest.AopSchedulerConfig.class) public class SchedulerIntegrationTest extends AbstractSchedulerTest { @Configuration @EnableScheduling @EnableSchedulerLock(interceptMode = PROXY_SCHEDULER, defaultLockAtMostFor = "PT30S") - public static class AopSchedulerConfig extends AbstractSchedulerConfig { - } + public static class AopSchedulerConfig extends AbstractSchedulerConfig {} } diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/BeanImpl.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/BeanImpl.java index 67d69dfd7..b7828db2e 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/BeanImpl.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/BeanImpl.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.proxytest; @@ -20,11 +18,8 @@ public class BeanImpl implements BeanInterface { - @Override @SchedulerLock(name = "test") @Async // to generate proxy - public void method() { - - } + public void method() {} } diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/BeanInterface.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/BeanInterface.java index fb0c5e9d6..873b48ef5 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/BeanInterface.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/BeanInterface.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.proxytest; diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/DynamicProxyConfig.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/DynamicProxyConfig.java index 11b4bba92..63eb1ab82 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/DynamicProxyConfig.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/DynamicProxyConfig.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.proxytest; @@ -27,5 +25,4 @@ public class DynamicProxyConfig { public BeanInterface bean() { return new BeanImpl(); } - } diff --git a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/SubclassProxyConfig.java b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/SubclassProxyConfig.java index 752f39073..c6af7b9f7 100644 --- a/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/SubclassProxyConfig.java +++ b/spring/shedlock-spring/src/test/java/net/javacrumbs/shedlock/spring/proxytest/SubclassProxyConfig.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.spring.proxytest; @@ -27,5 +25,4 @@ public class SubclassProxyConfig { public BeanInterface bean() { return new BeanImpl(); } - } diff --git a/spring/test/shedlock-springboot-future-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java b/spring/test/shedlock-springboot-future-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java index ba6280a65..f012d6f77 100644 --- a/spring/test/shedlock-springboot-future-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java +++ b/spring/test/shedlock-springboot-future-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java @@ -1,20 +1,19 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; +import javax.sql.DataSource; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider; import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; @@ -23,8 +22,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; -import javax.sql.DataSource; - @SpringBootApplication @EnableScheduling @EnableSchedulerLock(defaultLockAtMostFor = "PT10M") diff --git a/spring/test/shedlock-springboot-future-test/src/main/java/net/javacrumbs/shedlock/test/boot/HelloController.java b/spring/test/shedlock-springboot-future-test/src/main/java/net/javacrumbs/shedlock/test/boot/HelloController.java index ee947b04d..390611cc7 100644 --- a/spring/test/shedlock-springboot-future-test/src/main/java/net/javacrumbs/shedlock/test/boot/HelloController.java +++ b/spring/test/shedlock-springboot-future-test/src/main/java/net/javacrumbs/shedlock/test/boot/HelloController.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; @@ -25,5 +23,4 @@ public class HelloController { public String index() { return "Greetings from Spring Boot!"; } - } diff --git a/spring/test/shedlock-springboot-future-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java b/spring/test/shedlock-springboot-future-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java index c4d3b5498..c20467679 100644 --- a/spring/test/shedlock-springboot-future-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java +++ b/spring/test/shedlock-springboot-future-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java @@ -1,31 +1,28 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; -import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -import java.time.Duration; -import java.util.Date; - import static java.time.Duration.ZERO; import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; import static net.javacrumbs.shedlock.core.LockExtender.extendActiveLock; +import java.time.Duration; +import java.util.Date; +import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + @Component public class ScheduledTasks { @Scheduled(fixedRate = 100) diff --git a/spring/test/shedlock-springboot-future-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java b/spring/test/shedlock-springboot-future-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java index 32cc80060..a214b6abc 100644 --- a/spring/test/shedlock-springboot-future-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java +++ b/spring/test/shedlock-springboot-future-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java @@ -1,20 +1,24 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.condition.JRE.JAVA_17; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.verify; + import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; import org.junit.jupiter.api.Test; @@ -23,12 +27,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; -import static org.junit.jupiter.api.condition.JRE.JAVA_17; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.verify; - @SpringBootTest @EnabledForJreRange(min = JAVA_17) public class IntegrationTest { diff --git a/spring/test/shedlock-springboot-old-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java b/spring/test/shedlock-springboot-old-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java index 5079037a0..bb42ca267 100644 --- a/spring/test/shedlock-springboot-old-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java +++ b/spring/test/shedlock-springboot-old-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; diff --git a/spring/test/shedlock-springboot-old-test/src/main/java/net/javacrumbs/shedlock/test/boot/HelloController.java b/spring/test/shedlock-springboot-old-test/src/main/java/net/javacrumbs/shedlock/test/boot/HelloController.java index ee947b04d..390611cc7 100644 --- a/spring/test/shedlock-springboot-old-test/src/main/java/net/javacrumbs/shedlock/test/boot/HelloController.java +++ b/spring/test/shedlock-springboot-old-test/src/main/java/net/javacrumbs/shedlock/test/boot/HelloController.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; @@ -25,5 +23,4 @@ public class HelloController { public String index() { return "Greetings from Spring Boot!"; } - } diff --git a/spring/test/shedlock-springboot-old-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java b/spring/test/shedlock-springboot-old-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java index 71f0437d4..5aa040ce6 100644 --- a/spring/test/shedlock-springboot-old-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java +++ b/spring/test/shedlock-springboot-old-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java @@ -1,28 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; +import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; + +import java.util.Date; import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; -import java.util.Date; - -import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; - @Component public class ScheduledTasks { @Scheduled(fixedRate = 100) diff --git a/spring/test/shedlock-springboot-old-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java b/spring/test/shedlock-springboot-old-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java index b9864e4ca..23f984977 100644 --- a/spring/test/shedlock-springboot-old-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java +++ b/spring/test/shedlock-springboot-old-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java @@ -1,20 +1,23 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.verify; + import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; import org.junit.jupiter.api.Test; @@ -22,11 +25,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.verify; - @SpringBootTest public class IntegrationTest { @MockBean diff --git a/spring/test/shedlock-springboot-old-test/src/test/java/net/javacrumbs/shedlock/test/boot/LockUnitTest.java b/spring/test/shedlock-springboot-old-test/src/test/java/net/javacrumbs/shedlock/test/boot/LockUnitTest.java index 0380aa5a2..de7196871 100644 --- a/spring/test/shedlock-springboot-old-test/src/test/java/net/javacrumbs/shedlock/test/boot/LockUnitTest.java +++ b/spring/test/shedlock-springboot-old-test/src/test/java/net/javacrumbs/shedlock/test/boot/LockUnitTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; diff --git a/spring/test/shedlock-springboot-sleuth-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java b/spring/test/shedlock-springboot-sleuth-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java index 1982c5974..8b8d72eab 100644 --- a/spring/test/shedlock-springboot-sleuth-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java +++ b/spring/test/shedlock-springboot-sleuth-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java @@ -1,20 +1,19 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; +import javax.sql.DataSource; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider; import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; @@ -23,8 +22,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; -import javax.sql.DataSource; - @SpringBootApplication @EnableScheduling @EnableSchedulerLock(defaultLockAtMostFor = "PT10M") diff --git a/spring/test/shedlock-springboot-sleuth-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java b/spring/test/shedlock-springboot-sleuth-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java index 71f0437d4..5aa040ce6 100644 --- a/spring/test/shedlock-springboot-sleuth-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java +++ b/spring/test/shedlock-springboot-sleuth-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java @@ -1,28 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; +import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; + +import java.util.Date; import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; -import java.util.Date; - -import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; - @Component public class ScheduledTasks { @Scheduled(fixedRate = 100) diff --git a/spring/test/shedlock-springboot-sleuth-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java b/spring/test/shedlock-springboot-sleuth-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java index 55a147d73..c186b3348 100644 --- a/spring/test/shedlock-springboot-sleuth-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java +++ b/spring/test/shedlock-springboot-sleuth-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java @@ -1,20 +1,23 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.verify; + import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; import org.junit.jupiter.api.Test; @@ -22,11 +25,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.verify; - @SpringBootTest class IntegrationTest { diff --git a/spring/test/shedlock-springboot-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java b/spring/test/shedlock-springboot-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java index 95fa4f9e9..332124e7b 100644 --- a/spring/test/shedlock-springboot-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java +++ b/spring/test/shedlock-springboot-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java @@ -1,20 +1,19 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; +import javax.sql.DataSource; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider; import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; @@ -23,8 +22,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; -import javax.sql.DataSource; - @SpringBootApplication @EnableScheduling @EnableSchedulerLock(defaultLockAtMostFor = "10m") diff --git a/spring/test/shedlock-springboot-test/src/main/java/net/javacrumbs/shedlock/test/boot/HelloController.java b/spring/test/shedlock-springboot-test/src/main/java/net/javacrumbs/shedlock/test/boot/HelloController.java index ee947b04d..390611cc7 100644 --- a/spring/test/shedlock-springboot-test/src/main/java/net/javacrumbs/shedlock/test/boot/HelloController.java +++ b/spring/test/shedlock-springboot-test/src/main/java/net/javacrumbs/shedlock/test/boot/HelloController.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; @@ -25,5 +23,4 @@ public class HelloController { public String index() { return "Greetings from Spring Boot!"; } - } diff --git a/spring/test/shedlock-springboot-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java b/spring/test/shedlock-springboot-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java index 71f0437d4..5aa040ce6 100644 --- a/spring/test/shedlock-springboot-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java +++ b/spring/test/shedlock-springboot-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java @@ -1,28 +1,25 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; +import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; + +import java.util.Date; import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; -import java.util.Date; - -import static net.javacrumbs.shedlock.core.LockAssert.assertLocked; - @Component public class ScheduledTasks { @Scheduled(fixedRate = 100) diff --git a/spring/test/shedlock-springboot-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java b/spring/test/shedlock-springboot-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java index b9864e4ca..23f984977 100644 --- a/spring/test/shedlock-springboot-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java +++ b/spring/test/shedlock-springboot-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java @@ -1,20 +1,23 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.verify; + import net.javacrumbs.shedlock.core.LockConfiguration; import net.javacrumbs.shedlock.core.LockProvider; import org.junit.jupiter.api.Test; @@ -22,11 +25,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.verify; - @SpringBootTest public class IntegrationTest { @MockBean diff --git a/spring/test/shedlock-springboot-test/src/test/java/net/javacrumbs/shedlock/test/boot/LockUnitTest.java b/spring/test/shedlock-springboot-test/src/test/java/net/javacrumbs/shedlock/test/boot/LockUnitTest.java index 0380aa5a2..de7196871 100644 --- a/spring/test/shedlock-springboot-test/src/test/java/net/javacrumbs/shedlock/test/boot/LockUnitTest.java +++ b/spring/test/shedlock-springboot-test/src/test/java/net/javacrumbs/shedlock/test/boot/LockUnitTest.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; diff --git a/spring/test/shedlock-testng-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java b/spring/test/shedlock-testng-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java index 4ff163c32..369936ee1 100644 --- a/spring/test/shedlock-testng-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java +++ b/spring/test/shedlock-testng-test/src/main/java/net/javacrumbs/shedlock/test/boot/Application.java @@ -1,21 +1,20 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; import com.zaxxer.hikari.HikariDataSource; +import javax.sql.DataSource; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider; import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; @@ -25,8 +24,6 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.scheduling.annotation.EnableScheduling; -import javax.sql.DataSource; - @SpringBootApplication @EnableScheduling @EnableSchedulerLock(defaultLockAtMostFor = "PT10M") @@ -48,14 +45,16 @@ public DataSource dataSource() { datasource.setUsername("SA"); datasource.setPassword(""); - new JdbcTemplate(datasource).execute(""" - CREATE TABLE shedlock( - name VARCHAR(64),\s - lock_until TIMESTAMP(3) NULL,\s - locked_at TIMESTAMP(3) NULL,\s - locked_by VARCHAR(255),\s - PRIMARY KEY (name) - )"""); + new JdbcTemplate(datasource) + .execute( + """ + CREATE TABLE shedlock( + name VARCHAR(64),\s + lock_until TIMESTAMP(3) NULL,\s + locked_at TIMESTAMP(3) NULL,\s + locked_by VARCHAR(255),\s + PRIMARY KEY (name) + )"""); return datasource; } } diff --git a/spring/test/shedlock-testng-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java b/spring/test/shedlock-testng-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java index 3e674304b..cd54737f2 100644 --- a/spring/test/shedlock-testng-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java +++ b/spring/test/shedlock-testng-test/src/main/java/net/javacrumbs/shedlock/test/boot/ScheduledTasks.java @@ -1,16 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; @@ -23,7 +21,5 @@ public class ScheduledTasks { @Scheduled(fixedRate = 1) @SchedulerLock(name = "reportCurrentTime", lockAtLeastFor = "${lock.at.most.for}") - public void reportCurrentTime() { - - } + public void reportCurrentTime() {} } diff --git a/spring/test/shedlock-testng-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java b/spring/test/shedlock-testng-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java index 9902f0d82..78a20d5d5 100644 --- a/spring/test/shedlock-testng-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java +++ b/spring/test/shedlock-testng-test/src/test/java/net/javacrumbs/shedlock/test/boot/IntegrationTest.java @@ -1,30 +1,27 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package net.javacrumbs.shedlock.test.boot; +import static org.assertj.core.api.Assertions.assertThat; + +import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import javax.sql.DataSource; - -import static org.assertj.core.api.Assertions.assertThat; - @SpringBootTest public class IntegrationTest extends AbstractTestNGSpringContextTests { @Autowired From c89157a035ace9792c119aabef1668755d383570 Mon Sep 17 00:00:00 2001 From: Lukas Krecan Date: Wed, 1 Nov 2023 21:09:47 +0100 Subject: [PATCH 2/2] Spotless Kotlin --- pom.xml | 6 ++++++ .../javacrumbs/shedlock/test/boot/Application.kt | 16 ++++++---------- .../shedlock/test/boot/HelloController.kt | 13 +++++-------- .../shedlock/test/boot/ScheduledTasks.kt | 15 ++++++--------- .../shedlock/test/boot/IntegrationTest.kt | 16 ++++++---------- 5 files changed, 29 insertions(+), 37 deletions(-) diff --git a/pom.xml b/pom.xml index 8847cd75d..3d6e96cd8 100644 --- a/pom.xml +++ b/pom.xml @@ -101,6 +101,12 @@ 2.38.0 + + + 120 + + + diff --git a/spring/test/shedlock-springboot-kotlin-test/src/main/kotlin/net/javacrumbs/shedlock/test/boot/Application.kt b/spring/test/shedlock-springboot-kotlin-test/src/main/kotlin/net/javacrumbs/shedlock/test/boot/Application.kt index cd98478e6..9a5a8aba9 100644 --- a/spring/test/shedlock-springboot-kotlin-test/src/main/kotlin/net/javacrumbs/shedlock/test/boot/Application.kt +++ b/spring/test/shedlock-springboot-kotlin-test/src/main/kotlin/net/javacrumbs/shedlock/test/boot/Application.kt @@ -1,20 +1,18 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. */ package net.javacrumbs.shedlock.test.boot +import javax.sql.DataSource import net.javacrumbs.shedlock.core.LockProvider import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock @@ -23,8 +21,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.context.annotation.Bean import org.springframework.scheduling.annotation.EnableScheduling -import javax.sql.DataSource - @SpringBootApplication @EnableScheduling @EnableSchedulerLock(defaultLockAtMostFor = "PT10M") diff --git a/spring/test/shedlock-springboot-kotlin-test/src/main/kotlin/net/javacrumbs/shedlock/test/boot/HelloController.kt b/spring/test/shedlock-springboot-kotlin-test/src/main/kotlin/net/javacrumbs/shedlock/test/boot/HelloController.kt index b29f2e17c..c05e5d585 100644 --- a/spring/test/shedlock-springboot-kotlin-test/src/main/kotlin/net/javacrumbs/shedlock/test/boot/HelloController.kt +++ b/spring/test/shedlock-springboot-kotlin-test/src/main/kotlin/net/javacrumbs/shedlock/test/boot/HelloController.kt @@ -1,17 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. */ package net.javacrumbs.shedlock.test.boot diff --git a/spring/test/shedlock-springboot-kotlin-test/src/main/kotlin/net/javacrumbs/shedlock/test/boot/ScheduledTasks.kt b/spring/test/shedlock-springboot-kotlin-test/src/main/kotlin/net/javacrumbs/shedlock/test/boot/ScheduledTasks.kt index 0826df63c..993e6ab05 100644 --- a/spring/test/shedlock-springboot-kotlin-test/src/main/kotlin/net/javacrumbs/shedlock/test/boot/ScheduledTasks.kt +++ b/spring/test/shedlock-springboot-kotlin-test/src/main/kotlin/net/javacrumbs/shedlock/test/boot/ScheduledTasks.kt @@ -1,25 +1,22 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. */ package net.javacrumbs.shedlock.test.boot +import java.util.Date import net.javacrumbs.shedlock.core.LockAssert.assertLocked import net.javacrumbs.shedlock.spring.annotation.SchedulerLock import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component -import java.util.Date @Component class ScheduledTasks { diff --git a/spring/test/shedlock-springboot-kotlin-test/src/test/kotlin/net/javacrumbs/shedlock/test/boot/IntegrationTest.kt b/spring/test/shedlock-springboot-kotlin-test/src/test/kotlin/net/javacrumbs/shedlock/test/boot/IntegrationTest.kt index c924ca48f..0c87a1311 100644 --- a/spring/test/shedlock-springboot-kotlin-test/src/test/kotlin/net/javacrumbs/shedlock/test/boot/IntegrationTest.kt +++ b/spring/test/shedlock-springboot-kotlin-test/src/test/kotlin/net/javacrumbs/shedlock/test/boot/IntegrationTest.kt @@ -1,17 +1,14 @@ /** * Copyright 2009 the original author or authors. * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. */ package net.javacrumbs.shedlock.test.boot @@ -28,8 +25,7 @@ import org.springframework.boot.test.mock.mockito.MockBean @SpringBootTest class IntegrationTest { - @MockBean - private lateinit var lockProvider: LockProvider + @MockBean private lateinit var lockProvider: LockProvider @Test fun testScheduler() {