valueOperations;
24 | private final RedisTemplate redisTemplate;
25 | private final RedisConfigProperties redisProperties;
26 |
27 |
28 | public RedisIdempotentRepository(RedisTemplate redisTemplate, RedisConfigProperties redisProperties) {
29 | valueOperations = redisTemplate.opsForValue();
30 | this.redisTemplate = redisTemplate;
31 | this.redisProperties = redisProperties;
32 | }
33 |
34 | @Override
35 | public boolean contains(IdempotencyKey idempotencyKey) {
36 | return valueOperations.get(idempotencyKey.getKeyValue()) != null;
37 | }
38 |
39 | @Override
40 | public IdempotentResponseWrapper getResponse(IdempotencyKey idempotencyKey) {
41 | return valueOperations.get(idempotencyKey.getKeyValue()).getResponse();
42 | }
43 |
44 | @Override
45 | @Deprecated
46 | public void store(IdempotencyKey idempotencyKey, IdempotentRequestWrapper request) {
47 | valueOperations.set(idempotencyKey.getKeyValue(), prepareValue(request), redisProperties.getExpirationTimeHour(), TimeUnit.HOURS);
48 | }
49 |
50 | @Override
51 | public void store(IdempotencyKey idempotencyKey, IdempotentRequestWrapper request, Long ttl, TimeUnit timeUnit) {
52 | ttl = ttl == 0 ? redisProperties.getExpirationTimeHour() : ttl;
53 | valueOperations.set(idempotencyKey.getKeyValue(), prepareValue(request), ttl, timeUnit);
54 | }
55 |
56 | @Override
57 | public void remove(IdempotencyKey idempotencyKey) {
58 | redisTemplate.delete(idempotencyKey.getKeyValue());
59 | }
60 |
61 | @Override
62 | @Deprecated
63 | public void setResponse(IdempotencyKey idempotencyKey, IdempotentRequestWrapper request, IdempotentResponseWrapper response) {
64 | if (contains(idempotencyKey)) {
65 | IdempotentRequestResponseWrapper requestResponseWrapper = valueOperations.get(idempotencyKey);
66 | requestResponseWrapper.setResponse(response);
67 | valueOperations.set(idempotencyKey.getKeyValue(), prepareValue(request), redisProperties.getExpirationTimeHour(), TimeUnit.HOURS);
68 | }
69 | }
70 |
71 | /**
72 | * ttl describe
73 | *
74 | * @param idempotencyKey
75 | * @param request
76 | * @param response
77 | * @param ttl
78 | */
79 | @Override
80 | public void setResponse(IdempotencyKey idempotencyKey, IdempotentRequestWrapper request, IdempotentResponseWrapper response, Long ttl, TimeUnit timeUnit) {
81 | if (contains(idempotencyKey)) {
82 | ttl = ttl == 0 ? redisProperties.getExpirationTimeHour() : ttl;
83 | IdempotentRequestResponseWrapper requestResponseWrapper = valueOperations.get(idempotencyKey.getKeyValue());
84 | requestResponseWrapper.setResponse(response);
85 | valueOperations.set(idempotencyKey.getKeyValue(), prepareValue(request, response), ttl, timeUnit);
86 | }
87 | }
88 |
89 | /**
90 | * Prepares the value stored in redis
91 | *
92 | * if persistReqRes set to false,
93 | * it does not persist related request values in redis
94 | * @param request
95 | * @return
96 | */
97 | private IdempotentRequestResponseWrapper prepareValue(IdempotentRequestWrapper request) {
98 | if (redisProperties.getPersistReqRes()) {
99 | return new IdempotentRequestResponseWrapper(request);
100 | }
101 | return new IdempotentRequestResponseWrapper(null);
102 | }
103 |
104 | /**
105 | * Prepares the value stored in redis
106 | *
107 | * if persistReqRes set to false,
108 | * it does not persist related request and response values in redis
109 | * @param request
110 | * @param response
111 | * @return
112 | */
113 | private IdempotentRequestResponseWrapper prepareValue(IdempotentRequestWrapper request, IdempotentResponseWrapper response) {
114 | if (redisProperties.getPersistReqRes()) {
115 | return new IdempotentRequestResponseWrapper(request, response);
116 | }
117 | return new IdempotentRequestResponseWrapper(null);
118 | }
119 | }
120 |
121 |
--------------------------------------------------------------------------------
/examples/jdempotent-redis-example/.mvn/wrapper/MavenWrapperDownloader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2007-present the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | import java.net.*;
18 | import java.io.*;
19 | import java.nio.channels.*;
20 | import java.util.Properties;
21 |
22 | public class MavenWrapperDownloader {
23 |
24 | private static final String WRAPPER_VERSION = "0.5.6";
25 | /**
26 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
27 | */
28 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
29 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
30 |
31 | /**
32 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
33 | * use instead of the default one.
34 | */
35 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
36 | ".mvn/wrapper/maven-wrapper.properties";
37 |
38 | /**
39 | * Path where the maven-wrapper.jar will be saved to.
40 | */
41 | private static final String MAVEN_WRAPPER_JAR_PATH =
42 | ".mvn/wrapper/maven-wrapper.jar";
43 |
44 | /**
45 | * Name of the property which should be used to override the default download url for the wrapper.
46 | */
47 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
48 |
49 | public static void main(String args[]) {
50 | System.out.println("- Downloader started");
51 | File baseDirectory = new File(args[0]);
52 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
53 |
54 | // If the maven-wrapper.properties exists, read it and check if it contains a custom
55 | // wrapperUrl parameter.
56 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
57 | String url = DEFAULT_DOWNLOAD_URL;
58 | if (mavenWrapperPropertyFile.exists()) {
59 | FileInputStream mavenWrapperPropertyFileInputStream = null;
60 | try {
61 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
62 | Properties mavenWrapperProperties = new Properties();
63 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
64 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
65 | } catch (IOException e) {
66 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
67 | } finally {
68 | try {
69 | if (mavenWrapperPropertyFileInputStream != null) {
70 | mavenWrapperPropertyFileInputStream.close();
71 | }
72 | } catch (IOException e) {
73 | // Ignore ...
74 | }
75 | }
76 | }
77 | System.out.println("- Downloading from: " + url);
78 |
79 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
80 | if (!outputFile.getParentFile().exists()) {
81 | if (!outputFile.getParentFile().mkdirs()) {
82 | System.out.println(
83 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
84 | }
85 | }
86 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
87 | try {
88 | downloadFileFromURL(url, outputFile);
89 | System.out.println("Done");
90 | System.exit(0);
91 | } catch (Throwable e) {
92 | System.out.println("- Error downloading");
93 | e.printStackTrace();
94 | System.exit(1);
95 | }
96 | }
97 |
98 | private static void downloadFileFromURL(String urlString, File destination) throws Exception {
99 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
100 | String username = System.getenv("MVNW_USERNAME");
101 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
102 | Authenticator.setDefault(new Authenticator() {
103 | @Override
104 | protected PasswordAuthentication getPasswordAuthentication() {
105 | return new PasswordAuthentication(username, password);
106 | }
107 | });
108 | }
109 | URL website = new URL(urlString);
110 | ReadableByteChannel rbc;
111 | rbc = Channels.newChannel(website.openStream());
112 | FileOutputStream fos = new FileOutputStream(destination);
113 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
114 | fos.close();
115 | rbc.close();
116 | }
117 |
118 | }
119 |
--------------------------------------------------------------------------------
/examples/jdempotent-couchbase-example/.mvn/wrapper/MavenWrapperDownloader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2007-present the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | import java.net.*;
18 | import java.io.*;
19 | import java.nio.channels.*;
20 | import java.util.Properties;
21 |
22 | public class MavenWrapperDownloader {
23 |
24 | private static final String WRAPPER_VERSION = "0.5.6";
25 | /**
26 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
27 | */
28 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
29 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
30 |
31 | /**
32 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
33 | * use instead of the default one.
34 | */
35 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
36 | ".mvn/wrapper/maven-wrapper.properties";
37 |
38 | /**
39 | * Path where the maven-wrapper.jar will be saved to.
40 | */
41 | private static final String MAVEN_WRAPPER_JAR_PATH =
42 | ".mvn/wrapper/maven-wrapper.jar";
43 |
44 | /**
45 | * Name of the property which should be used to override the default download url for the wrapper.
46 | */
47 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
48 |
49 | public static void main(String args[]) {
50 | System.out.println("- Downloader started");
51 | File baseDirectory = new File(args[0]);
52 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
53 |
54 | // If the maven-wrapper.properties exists, read it and check if it contains a custom
55 | // wrapperUrl parameter.
56 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
57 | String url = DEFAULT_DOWNLOAD_URL;
58 | if (mavenWrapperPropertyFile.exists()) {
59 | FileInputStream mavenWrapperPropertyFileInputStream = null;
60 | try {
61 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
62 | Properties mavenWrapperProperties = new Properties();
63 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
64 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
65 | } catch (IOException e) {
66 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
67 | } finally {
68 | try {
69 | if (mavenWrapperPropertyFileInputStream != null) {
70 | mavenWrapperPropertyFileInputStream.close();
71 | }
72 | } catch (IOException e) {
73 | // Ignore ...
74 | }
75 | }
76 | }
77 | System.out.println("- Downloading from: " + url);
78 |
79 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
80 | if (!outputFile.getParentFile().exists()) {
81 | if (!outputFile.getParentFile().mkdirs()) {
82 | System.out.println(
83 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
84 | }
85 | }
86 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
87 | try {
88 | downloadFileFromURL(url, outputFile);
89 | System.out.println("Done");
90 | System.exit(0);
91 | } catch (Throwable e) {
92 | System.out.println("- Error downloading");
93 | e.printStackTrace();
94 | System.exit(1);
95 | }
96 | }
97 |
98 | private static void downloadFileFromURL(String urlString, File destination) throws Exception {
99 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
100 | String username = System.getenv("MVNW_USERNAME");
101 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
102 | Authenticator.setDefault(new Authenticator() {
103 | @Override
104 | protected PasswordAuthentication getPasswordAuthentication() {
105 | return new PasswordAuthentication(username, password);
106 | }
107 | });
108 | }
109 | URL website = new URL(urlString);
110 | ReadableByteChannel rbc;
111 | rbc = Channels.newChannel(website.openStream());
112 | FileOutputStream fos = new FileOutputStream(destination);
113 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
114 | fos.close();
115 | rbc.close();
116 | }
117 |
118 | }
119 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Jdempotent
2 |
3 | [](https://github.com/Trendyol/Jdempotent/actions/workflows/jdempotent-spring-boot-redis-starter.yml)
4 |
5 |
6 |
7 |
8 |
9 | # Goal of this Jdempotent-spring-boot-starter
10 |
11 | Make your endpoints idempotent easily
12 |
13 | # Usage
14 |
15 | 1. First of all, you need to add a dependency to pom.xml
16 |
17 | For Redis:
18 |
19 | ```xml
20 |
21 | com.trendyol
22 | Jdempotent-spring-boot-redis-starter
23 | 1.1.0
24 |
25 | ```
26 | For Couchbase:
27 |
28 | ```xml
29 |
30 | com.trendyol
31 | Jdempotent-spring-boot-couchbase-starter
32 | 1.1.0
33 |
34 | ```
35 |
36 | 2. You should add `@IdempotentResource` annotation to the method that you want to make idempotent resource, listener etc.
37 |
38 | ```java
39 | @IdempotentResource(cachePrefix = "WelcomingListener")
40 | @KafkaListener(topics = "trendyol.mail.welcome", groupId = "group_id")
41 | public void consumeMessage(@IdempotentRequestPayload String emailAdress) {
42 | SendEmailRequest request = SendEmailRequest.builder()
43 | .email(message)
44 | .subject(subject)
45 | .build();
46 |
47 | try {
48 | mailSenderService.sendMail(request);
49 | } catch (MessagingException e) {
50 | logger.error("MailSenderService.sendEmail() throw exception {} event: {} ", e, emailAdress);
51 |
52 | // Throwing any exception is enough to delete from redis. When successful, it will not be deleted from redis and will be idempotent.
53 | throw new RetryIdempotentRequestException(e);
54 | }
55 | }
56 | ```
57 |
58 | If want that idempotencyId in your payload. Put `@JdempotentId` annotation that places the generated idempotency identifier into annotated field.
59 | Can be thought of as @Id annotation in jpa.
60 |
61 | ```java
62 | public class IdempotentPayload {
63 | @JdempotentId
64 | private String jdempotentId;
65 | private Object data;
66 | }
67 | ```
68 |
69 | You might want to handle the name of the field differently to ensure idempotency. Just use @JdempotentProperty annotation needs to get the field name differently and generate the hash inspired by jackson (@JsonProperty annotation)
70 |
71 | ```java
72 | public class IdempotentPayload {
73 | @JdempotentProperty("userId")
74 | private String customerId;
75 | private Object data;
76 | }
77 | ```
78 |
79 |
80 | 3. If you want to handle a custom error case, you need to implement `ErrorConditionalCallback` like the following example:
81 |
82 | ```java
83 | @Component
84 | public class AspectConditionalCallback implements ErrorConditionalCallback {
85 |
86 | @Override
87 | public boolean onErrorCondition(Object response) {
88 | return response == IdempotentStateEnum.ERROR;
89 | }
90 |
91 | public RuntimeException onErrorCustomException() {
92 | return new RuntimeException("Status cannot be error");
93 | }
94 |
95 | }
96 | ```
97 |
98 | 4. Let's make the configuration:
99 |
100 | For redis configuration:
101 |
102 | ```yaml
103 | jdempotent:
104 | enable: true
105 | cache:
106 | redis:
107 | database: 1
108 | password: "password"
109 | sentinelHostList: 192.168.0.1,192.168.0.2,192.168.0.3
110 | sentinelPort: "26379"
111 | sentinelMasterName: "admin"
112 | expirationTimeHour: 2
113 | dialTimeoutSecond: 3
114 | readTimeoutSecond: 3
115 | writeTimeoutSecond: 3
116 | maxRetryCount: 3
117 | expireTimeoutHour: 3
118 | ```
119 |
120 | For couchbase configuration:
121 |
122 | ```yaml
123 | jdempotent:
124 | enable: true
125 | cryptography:
126 | algorithm: MD5
127 | cache:
128 | couchbase:
129 | connection-string: XXXXXXXX
130 | password: XXXXXXXX
131 | username: XXXXXXXX
132 | bucket-name: XXXXXXXX
133 | connect-timeout: 100000
134 | query-timeout: 20000
135 | kv-timeout: 3000
136 | ```
137 |
138 | Please note that you can disable Jdempotent easily if you need to.
139 | For example, assume that you don't have a circuit breaker and your Redis is down.
140 | In that case, you can disable Jdempotent with the following configuration:
141 |
142 |
143 | ```yaml
144 | enable: false
145 | ```
146 |
147 | ```java
148 | @SpringBootApplication(
149 | exclude = { RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class }
150 | )
151 | ```
152 |
153 | ## Performance
154 |
155 | As it is shown in the following image, the most cpu consuming part of Jdempotent is getting a Redis connection so we don't need to worry performance related issues.
156 |
157 |
158 |
159 |
160 |
161 | # Docs
162 |
163 | [Jdempotent Medium Article](https://medium.com/trendyol-tech/an-idempotency-library-jdempotent-5cd2cd0b76ff)
164 | [Jdempotent-core Javadoc](https://memojja.github.io/jdempotent-core/index.html)
165 | [Jdempotent-spring-boot-redis-starter Javadoc](https://memojja.github.io/jdempotent-spring-boot-redis-starter/index.html)
166 |
167 | ## Support
168 |
169 | [memojja's twitter](https://twitter.com/memojja)
170 |
171 | ## Licence
172 |
173 | [MIT Licence](https://opensource.org/licenses/MIT)
174 |
175 | ## Contributing
176 |
177 | 1. Fork it ( https://github.com/Trendyol/Jdempotent/fork )
178 | 2. Create your feature branch (git checkout -b my-new-feature)
179 | 3. Commit your changes (git commit -am 'Add some feature')
180 | 4. Push to the branch (git push origin my-new-feature)
181 | 5. Create a new Pull Request
182 |
183 | ## Contributors
184 |
185 | - [memojja](https://github.com/memojja) Mehmet ARI - creator, maintainer
186 |
--------------------------------------------------------------------------------
/Jdempotent-spring-boot-couchbase-starter/src/main/java/com/trendyol/jdempotent/couchbase/CouchbaseIdempotentRepository.java:
--------------------------------------------------------------------------------
1 | package com.trendyol.jdempotent.couchbase;
2 |
3 | import com.couchbase.client.java.Collection;
4 | import com.couchbase.client.java.kv.GetOptions;
5 | import com.couchbase.client.java.kv.GetResult;
6 | import com.couchbase.client.java.kv.UpsertOptions;
7 | import com.trendyol.jdempotent.core.datasource.IdempotentRepository;
8 | import com.trendyol.jdempotent.core.model.IdempotencyKey;
9 | import com.trendyol.jdempotent.core.model.IdempotentRequestResponseWrapper;
10 | import com.trendyol.jdempotent.core.model.IdempotentRequestWrapper;
11 | import com.trendyol.jdempotent.core.model.IdempotentResponseWrapper;
12 |
13 | import java.time.Duration;
14 | import java.util.HashMap;
15 | import java.util.Map;
16 | import java.util.concurrent.TimeUnit;
17 | import java.util.function.Function;
18 |
19 | /**
20 | * An implementation of the idempotent IdempotentRepository
21 | * that uses a distributed hash map from Couchbase
22 | *
23 | * That repository needs to store idempotent hash for idempotency check
24 | */
25 | public class CouchbaseIdempotentRepository implements IdempotentRepository {
26 | private final CouchbaseConfig couchbaseConfig;
27 | private final Collection collection;
28 | private Map> ttlConverter = new HashMap<>();
29 |
30 | public CouchbaseIdempotentRepository(CouchbaseConfig couchbaseConfig, Collection collection) {
31 | this.couchbaseConfig = couchbaseConfig;
32 | this.collection = collection;
33 | this.prepareTtlConverter();
34 | }
35 |
36 |
37 | @Override
38 | public boolean contains(IdempotencyKey key) {
39 | return collection.exists(key.getKeyValue()).exists();
40 | }
41 |
42 | @Override
43 | public IdempotentResponseWrapper getResponse(IdempotencyKey key) {
44 | return collection.get(key.getKeyValue(), GetOptions.getOptions().withExpiry(true)).contentAs(IdempotentRequestResponseWrapper.class).getResponse();
45 | }
46 |
47 | @Override
48 | public void store(IdempotencyKey key, IdempotentRequestWrapper requestObject) {
49 | collection.insert(key.getKeyValue(), prepareRequestValue(requestObject));
50 | }
51 |
52 | @Override
53 | public void store(IdempotencyKey key, IdempotentRequestWrapper requestObject, Long ttl, TimeUnit timeUnit) {
54 | Duration ttlDuration = getDurationByTttlAndTimeUnit(ttl, timeUnit);
55 | collection.upsert(
56 | key.getKeyValue(), prepareRequestValue(requestObject),
57 | UpsertOptions.upsertOptions().expiry(ttlDuration)
58 | );
59 | }
60 |
61 | @Override
62 | public void remove(IdempotencyKey key) {
63 | collection.remove(key.getKeyValue());
64 | }
65 |
66 | @Override
67 | public void setResponse(IdempotencyKey key, IdempotentRequestWrapper request, IdempotentResponseWrapper idempotentResponse) {
68 | if (contains(key)) {
69 | GetResult getResult = collection.get(key.getKeyValue(), GetOptions.getOptions().withExpiry(true));
70 | IdempotentRequestResponseWrapper requestResponseWrapper = prepareResponseValue(getResult,idempotentResponse);
71 | collection.upsert(key.getKeyValue(), requestResponseWrapper);
72 | }
73 | }
74 |
75 | @Override
76 | public void setResponse(IdempotencyKey key, IdempotentRequestWrapper request, IdempotentResponseWrapper idempotentResponse, Long ttl, TimeUnit timeUnit) {
77 | if (contains(key)) {
78 | GetResult getResult = collection.get(key.getKeyValue(),GetOptions.getOptions().withExpiry(true));
79 | IdempotentRequestResponseWrapper requestResponseWrapper = prepareResponseValue(getResult,idempotentResponse);
80 | collection.upsert(
81 | key.getKeyValue(),
82 | requestResponseWrapper,
83 | UpsertOptions.upsertOptions().expiry(getResult.expiry().get()));
84 | }
85 | }
86 |
87 | private Duration getDurationByTttlAndTimeUnit(Long ttl, TimeUnit timeUnit) {
88 | return ttlConverter.get(timeUnit).apply(ttl);
89 | }
90 |
91 | private void prepareTtlConverter() {
92 | ttlConverter.put(TimeUnit.DAYS, Duration::ofDays);
93 | ttlConverter.put(TimeUnit.HOURS, Duration::ofHours);
94 | ttlConverter.put(TimeUnit.MINUTES, Duration::ofMinutes);
95 | ttlConverter.put(TimeUnit.SECONDS, Duration::ofSeconds);
96 | ttlConverter.put(TimeUnit.MILLISECONDS, Duration::ofMillis);
97 | ttlConverter.put(TimeUnit.MICROSECONDS, Duration::ofMillis);
98 | ttlConverter.put(TimeUnit.NANOSECONDS, Duration::ofNanos);
99 | }
100 |
101 | /**
102 | * Prepares the request value stored in couchbase
103 | *
104 | * if persistReqRes set to false,
105 | * it does not persist related request and response values in couchbase
106 | * @param request
107 | * @return
108 | */
109 | private IdempotentRequestResponseWrapper prepareRequestValue(IdempotentRequestWrapper request) {
110 | if (couchbaseConfig.getPersistReqRes()) {
111 | return new IdempotentRequestResponseWrapper(request);
112 | }
113 | return new IdempotentRequestResponseWrapper(null);
114 | }
115 |
116 | /**
117 | * Prepares the response value stored in couchbase
118 | *
119 | * if persistReqRes set to false,
120 | * it does not persist related request and response values in redis
121 | * @param result
122 | * @param idempotentResponse
123 | * @return
124 | */
125 | private IdempotentRequestResponseWrapper prepareResponseValue(GetResult result,IdempotentResponseWrapper idempotentResponse) {
126 | IdempotentRequestResponseWrapper requestResponseWrapper = result.contentAs(IdempotentRequestResponseWrapper.class);
127 | if (couchbaseConfig.getPersistReqRes()) {
128 | requestResponseWrapper.setResponse(idempotentResponse);
129 | }
130 | return requestResponseWrapper;
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/examples/jdempotent-couchbase-example/mvnw.cmd:
--------------------------------------------------------------------------------
1 | @REM ----------------------------------------------------------------------------
2 | @REM Licensed to the Apache Software Foundation (ASF) under one
3 | @REM or more contributor license agreements. See the NOTICE file
4 | @REM distributed with this work for additional information
5 | @REM regarding copyright ownership. The ASF licenses this file
6 | @REM to you under the Apache License, Version 2.0 (the
7 | @REM "License"); you may not use this file except in compliance
8 | @REM with the License. You may obtain a copy of the License at
9 | @REM
10 | @REM https://www.apache.org/licenses/LICENSE-2.0
11 | @REM
12 | @REM Unless required by applicable law or agreed to in writing,
13 | @REM software distributed under the License is distributed on an
14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | @REM KIND, either express or implied. See the License for the
16 | @REM specific language governing permissions and limitations
17 | @REM under the License.
18 | @REM ----------------------------------------------------------------------------
19 |
20 | @REM ----------------------------------------------------------------------------
21 | @REM Maven Start Up Batch script
22 | @REM
23 | @REM Required ENV vars:
24 | @REM JAVA_HOME - location of a JDK home dir
25 | @REM
26 | @REM Optional ENV vars
27 | @REM M2_HOME - location of maven2's installed home dir
28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
31 | @REM e.g. to debug Maven itself, use
32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34 | @REM ----------------------------------------------------------------------------
35 |
36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
37 | @echo off
38 | @REM set title of command window
39 | title %0
40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
42 |
43 | @REM set %HOME% to equivalent of $HOME
44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
45 |
46 | @REM Execute a user defined script before this one
47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
51 | :skipRcPre
52 |
53 | @setlocal
54 |
55 | set ERROR_CODE=0
56 |
57 | @REM To isolate internal variables from possible post scripts, we use another setlocal
58 | @setlocal
59 |
60 | @REM ==== START VALIDATION ====
61 | if not "%JAVA_HOME%" == "" goto OkJHome
62 |
63 | echo.
64 | echo Error: JAVA_HOME not found in your environment. >&2
65 | echo Please set the JAVA_HOME variable in your environment to match the >&2
66 | echo location of your Java installation. >&2
67 | echo.
68 | goto error
69 |
70 | :OkJHome
71 | if exist "%JAVA_HOME%\bin\java.exe" goto init
72 |
73 | echo.
74 | echo Error: JAVA_HOME is set to an invalid directory. >&2
75 | echo JAVA_HOME = "%JAVA_HOME%" >&2
76 | echo Please set the JAVA_HOME variable in your environment to match the >&2
77 | echo location of your Java installation. >&2
78 | echo.
79 | goto error
80 |
81 | @REM ==== END VALIDATION ====
82 |
83 | :init
84 |
85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
86 | @REM Fallback to current working directory if not found.
87 |
88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
90 |
91 | set EXEC_DIR=%CD%
92 | set WDIR=%EXEC_DIR%
93 | :findBaseDir
94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
95 | cd ..
96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
97 | set WDIR=%CD%
98 | goto findBaseDir
99 |
100 | :baseDirFound
101 | set MAVEN_PROJECTBASEDIR=%WDIR%
102 | cd "%EXEC_DIR%"
103 | goto endDetectBaseDir
104 |
105 | :baseDirNotFound
106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
107 | cd "%EXEC_DIR%"
108 |
109 | :endDetectBaseDir
110 |
111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
112 |
113 | @setlocal EnableExtensions EnableDelayedExpansion
114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
116 |
117 | :endReadAdditionalConfig
118 |
119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
122 |
123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
124 |
125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
127 | )
128 |
129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data.
131 | if exist %WRAPPER_JAR% (
132 | if "%MVNW_VERBOSE%" == "true" (
133 | echo Found %WRAPPER_JAR%
134 | )
135 | ) else (
136 | if not "%MVNW_REPOURL%" == "" (
137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
138 | )
139 | if "%MVNW_VERBOSE%" == "true" (
140 | echo Couldn't find %WRAPPER_JAR%, downloading it ...
141 | echo Downloading from: %DOWNLOAD_URL%
142 | )
143 |
144 | powershell -Command "&{"^
145 | "$webclient = new-object System.Net.WebClient;"^
146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
148 | "}"^
149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
150 | "}"
151 | if "%MVNW_VERBOSE%" == "true" (
152 | echo Finished downloading %WRAPPER_JAR%
153 | )
154 | )
155 | @REM End of extension
156 |
157 | @REM Provide a "standardized" way to retrieve the CLI args that will
158 | @REM work with both Windows and non-Windows executions.
159 | set MAVEN_CMD_LINE_ARGS=%*
160 |
161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
162 | if ERRORLEVEL 1 goto error
163 | goto end
164 |
165 | :error
166 | set ERROR_CODE=1
167 |
168 | :end
169 | @endlocal & set ERROR_CODE=%ERROR_CODE%
170 |
171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
175 | :skipRcPost
176 |
177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause
179 |
180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
181 |
182 | exit /B %ERROR_CODE%
183 |
--------------------------------------------------------------------------------
/examples/jdempotent-redis-example/mvnw.cmd:
--------------------------------------------------------------------------------
1 | @REM ----------------------------------------------------------------------------
2 | @REM Licensed to the Apache Software Foundation (ASF) under one
3 | @REM or more contributor license agreements. See the NOTICE file
4 | @REM distributed with this work for additional information
5 | @REM regarding copyright ownership. The ASF licenses this file
6 | @REM to you under the Apache License, Version 2.0 (the
7 | @REM "License"); you may not use this file except in compliance
8 | @REM with the License. You may obtain a copy of the License at
9 | @REM
10 | @REM https://www.apache.org/licenses/LICENSE-2.0
11 | @REM
12 | @REM Unless required by applicable law or agreed to in writing,
13 | @REM software distributed under the License is distributed on an
14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | @REM KIND, either express or implied. See the License for the
16 | @REM specific language governing permissions and limitations
17 | @REM under the License.
18 | @REM ----------------------------------------------------------------------------
19 |
20 | @REM ----------------------------------------------------------------------------
21 | @REM Maven Start Up Batch script
22 | @REM
23 | @REM Required ENV vars:
24 | @REM JAVA_HOME - location of a JDK home dir
25 | @REM
26 | @REM Optional ENV vars
27 | @REM M2_HOME - location of maven2's installed home dir
28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
31 | @REM e.g. to debug Maven itself, use
32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34 | @REM ----------------------------------------------------------------------------
35 |
36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
37 | @echo off
38 | @REM set title of command window
39 | title %0
40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
42 |
43 | @REM set %HOME% to equivalent of $HOME
44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
45 |
46 | @REM Execute a user defined script before this one
47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
51 | :skipRcPre
52 |
53 | @setlocal
54 |
55 | set ERROR_CODE=0
56 |
57 | @REM To isolate internal variables from possible post scripts, we use another setlocal
58 | @setlocal
59 |
60 | @REM ==== START VALIDATION ====
61 | if not "%JAVA_HOME%" == "" goto OkJHome
62 |
63 | echo.
64 | echo Error: JAVA_HOME not found in your environment. >&2
65 | echo Please set the JAVA_HOME variable in your environment to match the >&2
66 | echo location of your Java installation. >&2
67 | echo.
68 | goto error
69 |
70 | :OkJHome
71 | if exist "%JAVA_HOME%\bin\java.exe" goto init
72 |
73 | echo.
74 | echo Error: JAVA_HOME is set to an invalid directory. >&2
75 | echo JAVA_HOME = "%JAVA_HOME%" >&2
76 | echo Please set the JAVA_HOME variable in your environment to match the >&2
77 | echo location of your Java installation. >&2
78 | echo.
79 | goto error
80 |
81 | @REM ==== END VALIDATION ====
82 |
83 | :init
84 |
85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
86 | @REM Fallback to current working directory if not found.
87 |
88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
90 |
91 | set EXEC_DIR=%CD%
92 | set WDIR=%EXEC_DIR%
93 | :findBaseDir
94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
95 | cd ..
96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
97 | set WDIR=%CD%
98 | goto findBaseDir
99 |
100 | :baseDirFound
101 | set MAVEN_PROJECTBASEDIR=%WDIR%
102 | cd "%EXEC_DIR%"
103 | goto endDetectBaseDir
104 |
105 | :baseDirNotFound
106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
107 | cd "%EXEC_DIR%"
108 |
109 | :endDetectBaseDir
110 |
111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
112 |
113 | @setlocal EnableExtensions EnableDelayedExpansion
114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
116 |
117 | :endReadAdditionalConfig
118 |
119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
122 |
123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
124 |
125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
127 | )
128 |
129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data.
131 | if exist %WRAPPER_JAR% (
132 | if "%MVNW_VERBOSE%" == "true" (
133 | echo Found %WRAPPER_JAR%
134 | )
135 | ) else (
136 | if not "%MVNW_REPOURL%" == "" (
137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
138 | )
139 | if "%MVNW_VERBOSE%" == "true" (
140 | echo Couldn't find %WRAPPER_JAR%, downloading it ...
141 | echo Downloading from: %DOWNLOAD_URL%
142 | )
143 |
144 | powershell -Command "&{"^
145 | "$webclient = new-object System.Net.WebClient;"^
146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
148 | "}"^
149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
150 | "}"
151 | if "%MVNW_VERBOSE%" == "true" (
152 | echo Finished downloading %WRAPPER_JAR%
153 | )
154 | )
155 | @REM End of extension
156 |
157 | @REM Provide a "standardized" way to retrieve the CLI args that will
158 | @REM work with both Windows and non-Windows executions.
159 | set MAVEN_CMD_LINE_ARGS=%*
160 |
161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
162 | if ERRORLEVEL 1 goto error
163 | goto end
164 |
165 | :error
166 | set ERROR_CODE=1
167 |
168 | :end
169 | @endlocal & set ERROR_CODE=%ERROR_CODE%
170 |
171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
175 | :skipRcPost
176 |
177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause
179 |
180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
181 |
182 | exit /B %ERROR_CODE%
183 |
--------------------------------------------------------------------------------
/Jdempotent-spring-boot-couchbase-starter/src/test/java/com/trendyol/jdempotent/couchbase/CouchbaseIdempotentRepositoryTest.java:
--------------------------------------------------------------------------------
1 | package com.trendyol.jdempotent.couchbase;
2 |
3 | import com.couchbase.client.java.Collection;
4 | import com.couchbase.client.java.kv.ExistsResult;
5 | import com.couchbase.client.java.kv.GetResult;
6 | import com.couchbase.client.java.kv.MutationResult;
7 | import com.couchbase.client.java.kv.UpsertOptions;
8 | import com.trendyol.jdempotent.core.model.IdempotencyKey;
9 | import com.trendyol.jdempotent.core.model.IdempotentRequestResponseWrapper;
10 | import com.trendyol.jdempotent.core.model.IdempotentRequestWrapper;
11 | import com.trendyol.jdempotent.core.model.IdempotentResponseWrapper;
12 | import org.junit.jupiter.api.BeforeEach;
13 | import org.junit.jupiter.api.Test;
14 | import org.junit.jupiter.api.extension.ExtendWith;
15 | import org.mockito.ArgumentCaptor;
16 | import org.mockito.Captor;
17 | import org.mockito.InjectMocks;
18 | import org.mockito.Mock;
19 | import org.mockito.junit.jupiter.MockitoExtension;
20 |
21 | import java.time.Duration;
22 | import java.util.Optional;
23 | import java.util.concurrent.TimeUnit;
24 |
25 | import static org.junit.Assert.assertFalse;
26 | import static org.junit.jupiter.api.Assertions.assertEquals;
27 | import static org.junit.jupiter.api.Assertions.assertTrue;
28 | import static org.mockito.Mockito.*;
29 |
30 | @ExtendWith(MockitoExtension.class)
31 | public class CouchbaseIdempotentRepositoryTest {
32 | @InjectMocks
33 | private CouchbaseIdempotentRepository couchbaseIdempotentRepository;
34 |
35 | @Mock
36 | private CouchbaseConfig couchbaseConfig;
37 |
38 | @Mock
39 | private Collection collection;
40 |
41 | @Captor
42 | private ArgumentCaptor captor;
43 |
44 | @Captor
45 | private ArgumentCaptor upsertOptionCaptor;
46 |
47 | @BeforeEach
48 | public void setUp() {
49 | couchbaseIdempotentRepository = new CouchbaseIdempotentRepository(couchbaseConfig,
50 | collection);
51 | }
52 |
53 | @Test
54 | public void given_an_available_object_when_couchbase_contains_then_return_true() {
55 | //Given
56 | IdempotencyKey idempotencyKey = new IdempotencyKey("key");
57 | ExistsResult existsResult = mock(ExistsResult.class);
58 | when(existsResult.exists()).thenReturn(true);
59 | when(collection.exists(idempotencyKey.getKeyValue())).thenReturn(existsResult);
60 |
61 | //When
62 | Boolean isContain = couchbaseIdempotentRepository.contains(idempotencyKey);
63 |
64 | //Then
65 | verify(collection, times(1)).exists(idempotencyKey.getKeyValue());
66 | assertTrue(isContain);
67 | }
68 |
69 | @Test
70 | public void given_an_available_object_when_couchbase_contains_then_return_false() {
71 | //Given
72 | IdempotencyKey idempotencyKey = new IdempotencyKey("key");
73 | ExistsResult existsResult = mock(ExistsResult.class);
74 | when(existsResult.exists()).thenReturn(false);
75 | when(collection.exists(idempotencyKey.getKeyValue())).thenReturn(existsResult);
76 |
77 | //When
78 | Boolean isContain = couchbaseIdempotentRepository.contains(idempotencyKey);
79 |
80 | //Then
81 | verify(collection, times(1)).exists(idempotencyKey.getKeyValue());
82 | assertFalse(isContain);
83 | }
84 |
85 | @Test
86 | public void given_an_available_object_when_couchbase_get_response_then_return_expected_idempotent_response_wrapper() {
87 | //Given
88 | IdempotencyKey idempotencyKey = new IdempotencyKey("key");
89 | IdempotentRequestResponseWrapper wrapper = new IdempotentRequestResponseWrapper();
90 | GetResult getResult = mock(GetResult.class);
91 | when(getResult.contentAs(IdempotentRequestResponseWrapper.class)).thenReturn(wrapper);
92 | when(collection.get(eq(idempotencyKey.getKeyValue()),any())).thenReturn(getResult);
93 |
94 | //When
95 | IdempotentResponseWrapper result = couchbaseIdempotentRepository.getResponse(idempotencyKey);
96 |
97 | //Then
98 | verify(collection, times(1)).get(eq(idempotencyKey.getKeyValue()),any());
99 | assertEquals(result, wrapper.getResponse());
100 | }
101 |
102 | @Test
103 | public void given_an_available_object_when_couchbase_store_then_collection_insert_once_time() {
104 | //Given
105 | IdempotencyKey idempotencyKey = new IdempotencyKey("key");
106 | IdempotentRequestWrapper wrapper = new IdempotentRequestWrapper();
107 | IdempotentRequestResponseWrapper responseWrapper = new IdempotentRequestResponseWrapper(wrapper);
108 |
109 | //When
110 | couchbaseIdempotentRepository.store(idempotencyKey, wrapper);
111 |
112 | //Then
113 | verify(collection, times(1)).insert(eq(idempotencyKey.getKeyValue()), captor.capture());
114 | IdempotentRequestResponseWrapper idempotentRequestResponseWrapper = captor.getValue();
115 | assertEquals(idempotentRequestResponseWrapper.getResponse(), responseWrapper.getResponse());
116 | }
117 |
118 | @Test
119 | public void given_an_available_object_when_couchbase_store_with_ttl_and_time_unit_is_days_then_collection_insert_once_time() {
120 | //Given
121 | IdempotencyKey idempotencyKey = new IdempotencyKey("key");
122 | IdempotentRequestWrapper wrapper = new IdempotentRequestWrapper();
123 | Long ttl = 1L;
124 | TimeUnit timeUnit = TimeUnit.DAYS;
125 | IdempotentRequestResponseWrapper responseWrapper = new IdempotentRequestResponseWrapper(wrapper);
126 |
127 | //When
128 | couchbaseIdempotentRepository.store(idempotencyKey, wrapper, ttl, timeUnit);
129 |
130 | //Then
131 | verify(collection, times(1)).upsert(eq(idempotencyKey.getKeyValue()),
132 | captor.capture(),
133 | upsertOptionCaptor.capture());
134 | IdempotentRequestResponseWrapper idempotentRequestResponseWrapper = captor.getValue();
135 | assertEquals(idempotentRequestResponseWrapper.getResponse(), responseWrapper.getResponse());
136 | }
137 |
138 |
139 | @Test
140 | public void setResponse() {
141 | //Given
142 | IdempotencyKey idempotencyKey = new IdempotencyKey("key");
143 | IdempotentRequestResponseWrapper wrapper = new IdempotentRequestResponseWrapper();
144 | GetResult getResult = mock(GetResult.class);
145 | ExistsResult existsResult = mock(ExistsResult.class);
146 | when(existsResult.exists()).thenReturn(true);
147 | when(getResult.contentAs(IdempotentRequestResponseWrapper.class)).thenReturn(wrapper);
148 |
149 | when(collection.get(eq(idempotencyKey.getKeyValue()),any())).thenReturn(getResult);
150 | when(collection.exists(idempotencyKey.getKeyValue())).thenReturn(existsResult);
151 | when(collection.upsert(idempotencyKey.getKeyValue(),wrapper)).thenReturn(mock(MutationResult.class));
152 | //When
153 | couchbaseIdempotentRepository.setResponse(idempotencyKey,mock(IdempotentRequestWrapper.class),
154 | mock(IdempotentResponseWrapper.class));
155 |
156 | //Then
157 | verify(collection, times(1)).get(eq(idempotencyKey.getKeyValue()),any());
158 | }
159 |
160 | @Test
161 | public void setResponse_when_given_a_ttl() {
162 | //Given
163 | IdempotencyKey idempotencyKey = new IdempotencyKey("key");
164 | IdempotentRequestResponseWrapper wrapper = new IdempotentRequestResponseWrapper();
165 | GetResult getResult = mock(GetResult.class);
166 | ExistsResult existsResult = mock(ExistsResult.class);
167 | when(existsResult.exists()).thenReturn(true);
168 | when(getResult.contentAs(IdempotentRequestResponseWrapper.class)).thenReturn(wrapper);
169 | when(getResult.expiry()).thenReturn(Optional.of(mock(Duration.class)));
170 | when(collection.get(eq(idempotencyKey.getKeyValue()),any())).thenReturn(getResult);
171 | when(collection.exists(idempotencyKey.getKeyValue())).thenReturn(existsResult);
172 | when(collection.upsert(eq(idempotencyKey.getKeyValue()),eq(wrapper),any())).thenReturn(mock(MutationResult.class));
173 | //When
174 | couchbaseIdempotentRepository.setResponse(idempotencyKey,mock(IdempotentRequestWrapper.class),
175 | mock(IdempotentResponseWrapper.class),5L,TimeUnit.DAYS);
176 |
177 | //Then
178 | verify(collection, times(1)).get(eq(idempotencyKey.getKeyValue()),any());
179 | }
180 | }
--------------------------------------------------------------------------------
/Jdempotent-core/src/test/java/aspect/withaspect/IdempotentAspectIT.java:
--------------------------------------------------------------------------------
1 | package aspect.withaspect;
2 |
3 | import aspect.core.IdempotentTestPayload;
4 | import aspect.core.TestException;
5 | import aspect.core.TestIdempotentResource;
6 | import com.trendyol.jdempotent.core.annotation.JdempotentResource;
7 | import com.trendyol.jdempotent.core.constant.CryptographyAlgorithm;
8 | import com.trendyol.jdempotent.core.datasource.InMemoryIdempotentRepository;
9 | import com.trendyol.jdempotent.core.generator.DefaultKeyGenerator;
10 | import com.trendyol.jdempotent.core.model.IdempotencyKey;
11 | import com.trendyol.jdempotent.core.model.IdempotentIgnorableWrapper;
12 | import com.trendyol.jdempotent.core.model.IdempotentRequestWrapper;
13 | import org.junit.Test;
14 | import org.junit.runner.RunWith;
15 | import org.springframework.aop.framework.AopProxyUtils;
16 | import org.springframework.aop.support.AopUtils;
17 | import org.springframework.beans.factory.annotation.Autowired;
18 | import org.springframework.test.context.ContextConfiguration;
19 | import org.springframework.test.context.junit4.SpringRunner;
20 | import org.springframework.test.util.AopTestUtils;
21 |
22 | import java.security.MessageDigest;
23 | import java.security.NoSuchAlgorithmException;
24 |
25 | import static org.junit.Assert.*;
26 |
27 | @RunWith(SpringRunner.class)
28 | @ContextConfiguration(classes = {IdempotentAspectIT.class, TestAopContext.class, TestIdempotentResource.class, DefaultKeyGenerator.class, InMemoryIdempotentRepository.class})
29 | public class IdempotentAspectIT {
30 |
31 | @Autowired
32 | private TestIdempotentResource testIdempotentResource;
33 |
34 | @Autowired
35 | private InMemoryIdempotentRepository idempotentRepository;
36 |
37 | @Autowired
38 | private DefaultKeyGenerator defaultKeyGenerator;
39 |
40 |
41 | @Test
42 | public void given_aop_context_then_run_with_aop_context() {
43 | JdempotentResource jdempotentResource = TestIdempotentResource.class.getDeclaredMethods()[0].getAnnotation(JdempotentResource.class);
44 |
45 | assertNotEquals(testIdempotentResource.getClass(), TestIdempotentResource.class);
46 | assertTrue(AopUtils.isAopProxy(testIdempotentResource));
47 | assertTrue(AopUtils.isCglibProxy(testIdempotentResource));
48 | assertNotNull(jdempotentResource);
49 |
50 | assertEquals(AopProxyUtils.ultimateTargetClass(testIdempotentResource), TestIdempotentResource.class);
51 | assertEquals(AopTestUtils.getTargetObject(testIdempotentResource).getClass(), TestIdempotentResource.class);
52 | assertEquals(AopTestUtils.getUltimateTargetObject(testIdempotentResource).getClass(), TestIdempotentResource.class);
53 | }
54 |
55 | @Test
56 | public void given_new_payload_when_trigger_aspect_then_that_will_be_aviable_in_repository() throws NoSuchAlgorithmException {
57 | //given
58 | IdempotentTestPayload test = new IdempotentTestPayload();
59 | IdempotentIgnorableWrapper wrapper = new IdempotentIgnorableWrapper();
60 | wrapper.getNonIgnoredFields().put("name", null);
61 |
62 | IdempotencyKey idempotencyKey = defaultKeyGenerator.generateIdempotentKey(new IdempotentRequestWrapper(wrapper), "", new StringBuilder(), MessageDigest.getInstance(CryptographyAlgorithm.MD5.value()));
63 |
64 | //when
65 | testIdempotentResource.idempotentMethod(test);
66 |
67 | //then
68 | assertTrue(idempotentRepository.contains(idempotencyKey));
69 | }
70 |
71 | @Test
72 | public void given_new_multiple_payloads_when_trigger_aspect_then_that_will_be_available_in_repository() throws NoSuchAlgorithmException {
73 | //given
74 | IdempotentTestPayload test = new IdempotentTestPayload();
75 | IdempotentTestPayload test1 = new IdempotentTestPayload();
76 | IdempotentTestPayload test2 = new IdempotentTestPayload();
77 | IdempotentIgnorableWrapper wrapper = new IdempotentIgnorableWrapper();
78 | wrapper.getNonIgnoredFields().put("name", null);
79 |
80 | IdempotencyKey idempotencyKey = defaultKeyGenerator.generateIdempotentKey(new IdempotentRequestWrapper(wrapper), "TestIdempotentResource", new StringBuilder(), MessageDigest.getInstance(CryptographyAlgorithm.MD5.value()));
81 |
82 | //when
83 | testIdempotentResource.idempotentMethodWithThreeParameter(test, test1, test2);
84 |
85 | //then
86 | assertTrue(idempotentRepository.contains(idempotencyKey));
87 | }
88 |
89 | @Test(expected = TestException.class)
90 | public void given_invalid_payload_when_trigger_aspect_then_throw_test_exception_and_repository_will_be_empty() throws NoSuchAlgorithmException {
91 | //given
92 | IdempotentTestPayload test = new IdempotentTestPayload();
93 | test.setName("invalid");
94 | IdempotentIgnorableWrapper wrapper = new IdempotentIgnorableWrapper();
95 | wrapper.getNonIgnoredFields().put("name", "invalid");
96 |
97 | IdempotencyKey idempotencyKey = defaultKeyGenerator.generateIdempotentKey(new IdempotentRequestWrapper(wrapper), "TestIdempotentResource", new StringBuilder(), MessageDigest.getInstance(CryptographyAlgorithm.MD5.value()));
98 |
99 | //when
100 | testIdempotentResource.idempotentMethodThrowingARuntimeException(test);
101 |
102 | //then
103 | assertFalse(idempotentRepository.contains(idempotencyKey));
104 | }
105 |
106 | @Test
107 | public void given_new_multiple_payloads_with_multiple_annotations_when_trigger_aspect_then_first_annotated_payload_that_will_be_available_in_repository() throws NoSuchAlgorithmException {
108 | //given
109 | IdempotentTestPayload test = new IdempotentTestPayload();
110 | IdempotentTestPayload test1 = new IdempotentTestPayload();
111 | Object test2 = new Object();
112 | IdempotentIgnorableWrapper wrapper = new IdempotentIgnorableWrapper();
113 | wrapper.getNonIgnoredFields().put("name", null);
114 | IdempotencyKey idempotencyKey = defaultKeyGenerator.generateIdempotentKey(new IdempotentRequestWrapper(wrapper), "TestIdempotentResource", new StringBuilder(), MessageDigest.getInstance(CryptographyAlgorithm.MD5.value()));
115 |
116 | //when
117 | testIdempotentResource.idempotentMethodWithThreeParamaterAndMultipleJdempotentRequestPayloadAnnotation(test, test1, test2);
118 |
119 | //then
120 | assertTrue(idempotentRepository.contains(idempotencyKey));
121 | }
122 |
123 | @Test(expected = IllegalStateException.class)
124 | public void given_no_args_when_trigger_aspect_then_throw_illegal_state_exception() throws NoSuchAlgorithmException {
125 | //given
126 | //when
127 | //then
128 | testIdempotentResource.idempotentMethodWithZeroParamater();
129 | }
130 |
131 | @Test(expected = IllegalStateException.class)
132 | public void given_multiple_args_without_idempotent_request_annotation_when_trigger_aspect_then_throw_illegal_state_exception() throws NoSuchAlgorithmException {
133 | //given
134 | IdempotentTestPayload test = new IdempotentTestPayload();
135 | IdempotentTestPayload test1 = new IdempotentTestPayload();
136 |
137 | //when
138 | //then
139 | testIdempotentResource.methodWithTwoParamater(test, test1);
140 | }
141 |
142 | @Test
143 | public void given_jdempotent_id_then_args_should_have_idempotency_id() throws NoSuchAlgorithmException {
144 | //given
145 | IdempotentTestPayload test = new IdempotentTestPayload();
146 | IdempotentIgnorableWrapper wrapper = new IdempotentIgnorableWrapper();
147 | wrapper.getNonIgnoredFields().put("name", null);
148 |
149 | IdempotencyKey idempotencyKey = defaultKeyGenerator.generateIdempotentKey(new IdempotentRequestWrapper(wrapper), "", new StringBuilder(), MessageDigest.getInstance(CryptographyAlgorithm.MD5.value()));
150 |
151 | //when
152 | testIdempotentResource.idempotentMethod(test);
153 |
154 | //then
155 | assertTrue(idempotentRepository.contains(idempotencyKey));
156 | }
157 |
158 | @Test
159 | public void given_new_payload_as_string_when_trigger_aspect_then_that_will_be_aviable_in_repository() throws NoSuchAlgorithmException {
160 | //given
161 | String idempotencyKey = "key";
162 | IdempotentTestPayload test = new IdempotentTestPayload();
163 | IdempotentIgnorableWrapper wrapper = new IdempotentIgnorableWrapper();
164 | wrapper.getNonIgnoredFields().put(idempotencyKey, idempotencyKey);
165 | IdempotencyKey key = defaultKeyGenerator.generateIdempotentKey(new IdempotentRequestWrapper(wrapper), "", new StringBuilder(), MessageDigest.getInstance(CryptographyAlgorithm.MD5.value()));
166 |
167 | //when
168 | testIdempotentResource.idempotencyKeyAsString(idempotencyKey);
169 |
170 | //then
171 | assertTrue(idempotentRepository.contains(key));
172 | }
173 |
174 | }
--------------------------------------------------------------------------------
/Jdempotent-spring-boot-redis-starter/src/test/java/RedisIdempotentRepositoryTest.java:
--------------------------------------------------------------------------------
1 | import com.trendyol.jdempotent.core.model.IdempotencyKey;
2 | import com.trendyol.jdempotent.core.model.IdempotentRequestResponseWrapper;
3 | import com.trendyol.jdempotent.core.model.IdempotentRequestWrapper;
4 | import com.trendyol.jdempotent.core.model.IdempotentResponseWrapper;
5 | import com.trendyol.jdempotent.redis.RedisConfigProperties;
6 | import com.trendyol.jdempotent.redis.RedisIdempotentRepository;
7 | import org.junit.jupiter.api.BeforeEach;
8 | import org.junit.jupiter.api.Test;
9 | import org.junit.jupiter.api.extension.ExtendWith;
10 | import org.mockito.ArgumentCaptor;
11 | import org.mockito.Captor;
12 | import org.mockito.InjectMocks;
13 | import org.mockito.Mock;
14 | import org.mockito.junit.jupiter.MockitoExtension;
15 | import org.springframework.data.redis.core.RedisTemplate;
16 | import org.springframework.data.redis.core.ValueOperations;
17 |
18 | import java.util.concurrent.TimeUnit;
19 |
20 | import static org.junit.jupiter.api.Assertions.assertEquals;
21 | import static org.junit.jupiter.api.Assertions.assertFalse;
22 | import static org.junit.jupiter.api.Assertions.assertNull;
23 | import static org.junit.jupiter.api.Assertions.assertTrue;
24 | import static org.mockito.ArgumentMatchers.any;
25 | import static org.mockito.ArgumentMatchers.eq;
26 | import static org.mockito.Mockito.mock;
27 | import static org.mockito.Mockito.times;
28 | import static org.mockito.Mockito.verify;
29 | import static org.mockito.Mockito.when;
30 |
31 | @ExtendWith(MockitoExtension.class)
32 | public class RedisIdempotentRepositoryTest {
33 |
34 |
35 | @InjectMocks
36 | private RedisIdempotentRepository redisIdempotentRepository;
37 |
38 | @Mock
39 | private RedisTemplate redisTemplate;
40 |
41 | @Mock
42 | private RedisConfigProperties redisConfigProperties;
43 |
44 | @Mock
45 | private ValueOperations valueOperations;
46 |
47 | @Captor
48 | private ArgumentCaptor captor;
49 |
50 | @BeforeEach
51 | public void setUp() {
52 | when(redisTemplate.opsForValue()).thenReturn(valueOperations);
53 | redisIdempotentRepository = new RedisIdempotentRepository(redisTemplate,
54 | redisConfigProperties);
55 | }
56 |
57 | @Test
58 | public void given_an_available_object_when_redis_contains_then_return_true() {
59 | //Given
60 | IdempotencyKey idempotencyKey = new IdempotencyKey("key");
61 | var key = new IdempotencyKey("key");
62 | var wrapper = new IdempotentRequestResponseWrapper(
63 | new IdempotentRequestWrapper(new Object()));
64 | when(valueOperations.get(key.getKeyValue())).thenReturn(wrapper);
65 |
66 | //When
67 | Boolean isContain = redisIdempotentRepository.contains(idempotencyKey);
68 |
69 | //Then
70 | verify(valueOperations, times(1)).get(idempotencyKey.getKeyValue());
71 | assertTrue(isContain);
72 | }
73 |
74 | @Test
75 | public void given_an_unavailable_object_when_redis_contains_then_return_false() {
76 | //Given
77 | IdempotencyKey idempotencyKey = new IdempotencyKey("key1");
78 |
79 | //When
80 | Boolean isContain = redisIdempotentRepository.contains(idempotencyKey);
81 |
82 | //Then
83 | verify(valueOperations, times(1)).get(idempotencyKey.getKeyValue());
84 | assertFalse(isContain);
85 | }
86 |
87 | @Test
88 | public void given_an_available_object_when_get_response_then_return_response() {
89 | //Given
90 | var key = new IdempotencyKey("key");
91 | var wrapper = new IdempotentRequestResponseWrapper(
92 | new IdempotentRequestWrapper(new Object()));
93 | when(valueOperations.get(key.getKeyValue())).thenReturn(wrapper);
94 | var t = mock(IdempotentRequestResponseWrapper.class);
95 |
96 | IdempotentResponseWrapper expected = new IdempotentResponseWrapper("testt");
97 | when(t.getResponse()).thenReturn(expected);
98 | when(valueOperations.get(key.getKeyValue())).thenReturn(t);
99 |
100 | //When
101 | IdempotentResponseWrapper response = redisIdempotentRepository.getResponse(key);
102 |
103 | //Then
104 | verify(t).getResponse();
105 | assertEquals(response.getResponse(), "testt");
106 | }
107 |
108 | @Test
109 | public void given_idempotency_key_and_request_object_when_store_then_set_value_to_redis() {
110 | //Given
111 | IdempotencyKey key = new IdempotencyKey("key");
112 | IdempotentRequestWrapper request = new IdempotentRequestWrapper(123L);
113 | when(redisConfigProperties.getPersistReqRes()).thenReturn(true);
114 |
115 | //When
116 | redisIdempotentRepository.store(key, request, 1L, TimeUnit.HOURS);
117 |
118 | //Then
119 | var argumentCaptor = ArgumentCaptor.forClass(IdempotentRequestResponseWrapper.class);
120 | verify(valueOperations).set(eq(key.getKeyValue()), argumentCaptor.capture(), eq(1L), eq(TimeUnit.HOURS));
121 | IdempotentRequestResponseWrapper value = argumentCaptor.getValue();
122 | assertEquals(value.getRequest().getRequest(), 123L);
123 | }
124 |
125 | @Test
126 | public void given_ttl_zero_when_store_then_set_value_to_redis_with_property_ttl() {
127 | //Given
128 | IdempotencyKey key = new IdempotencyKey("key");
129 | IdempotentRequestWrapper request = new IdempotentRequestWrapper(123L);
130 | when(redisConfigProperties.getExpirationTimeHour()).thenReturn(99L);
131 |
132 | //When
133 | redisIdempotentRepository.store(key, request, 0L, TimeUnit.HOURS);
134 |
135 | //Then
136 | verify(valueOperations).set(eq(key.getKeyValue()), any(), eq(99L), eq(TimeUnit.HOURS));
137 | }
138 |
139 | @Test
140 | public void given_idempotency_key_when_remove_then_delete_redis_key() {
141 | //Given
142 | IdempotencyKey key = new IdempotencyKey("key");
143 |
144 | //When
145 | redisIdempotentRepository.remove(key);
146 |
147 | //Then
148 | verify(redisTemplate).delete(eq(key.getKeyValue()));
149 | }
150 |
151 | @Test
152 | public void given_idempotency_key_and_request_and_response_objects_when_set_response_then_set_response_to_key() {
153 | //Given
154 | IdempotencyKey key = new IdempotencyKey("key");
155 | IdempotentRequestWrapper request = new IdempotentRequestWrapper(123L);
156 | IdempotentResponseWrapper response = new IdempotentResponseWrapper("response");
157 | var wrapper = new IdempotentRequestResponseWrapper(
158 | new IdempotentRequestWrapper(new Object()));
159 | when(valueOperations.get(key.getKeyValue())).thenReturn(wrapper);
160 | assertNull(wrapper.getResponse());
161 | when(redisConfigProperties.getPersistReqRes()).thenReturn(true);
162 |
163 | //When
164 | redisIdempotentRepository.setResponse(key, request, response, 1L, TimeUnit.HOURS);
165 |
166 | //Then
167 | var argumentCaptor = ArgumentCaptor.forClass(IdempotentRequestResponseWrapper.class);
168 | verify(valueOperations).set(eq(key.getKeyValue()), argumentCaptor.capture(), eq(1L), eq(TimeUnit.HOURS));
169 | IdempotentRequestResponseWrapper value = argumentCaptor.getValue();
170 | assertEquals(value.getRequest().getRequest(), 123L);
171 | assertEquals(value.getResponse().getResponse(), "response");
172 | assertEquals(wrapper.getResponse().getResponse(), "response");
173 | }
174 |
175 | @Test
176 | public void given_the_idempotence_key_and_the_request_and_response_objects_when_defining_the_response_one_must_save_the_key_without_the_request_and_response_object() {
177 | //Given
178 | IdempotencyKey key = new IdempotencyKey("key");
179 | IdempotentRequestWrapper request = new IdempotentRequestWrapper(123L);
180 | IdempotentResponseWrapper response = new IdempotentResponseWrapper("response");
181 | var wrapper = new IdempotentRequestResponseWrapper(
182 | new IdempotentRequestWrapper(new Object()));
183 | when(valueOperations.get(key.getKeyValue())).thenReturn(wrapper);
184 | assertNull(wrapper.getResponse());
185 | when(redisConfigProperties.getPersistReqRes()).thenReturn(false);
186 |
187 | //When
188 | redisIdempotentRepository.setResponse(key, request, response, 1L, TimeUnit.HOURS);
189 |
190 | //Then
191 | var argumentCaptor = ArgumentCaptor.forClass(IdempotentRequestResponseWrapper.class);
192 | verify(valueOperations).set(eq(key.getKeyValue()), argumentCaptor.capture(), eq(1L), eq(TimeUnit.HOURS));
193 | IdempotentRequestResponseWrapper value = argumentCaptor.getValue();
194 | assertNull(value.getRequest());
195 | assertNull(value.getResponse());
196 | assertEquals(wrapper.getResponse().getResponse(), "response");
197 | }
198 | }
--------------------------------------------------------------------------------
/examples/jdempotent-redis-example/mvnw:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # ----------------------------------------------------------------------------
3 | # Licensed to the Apache Software Foundation (ASF) under one
4 | # or more contributor license agreements. See the NOTICE file
5 | # distributed with this work for additional information
6 | # regarding copyright ownership. The ASF licenses this file
7 | # to you under the Apache License, Version 2.0 (the
8 | # "License"); you may not use this file except in compliance
9 | # with the License. You may obtain a copy of the License at
10 | #
11 | # https://www.apache.org/licenses/LICENSE-2.0
12 | #
13 | # Unless required by applicable law or agreed to in writing,
14 | # software distributed under the License is distributed on an
15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 | # KIND, either express or implied. See the License for the
17 | # specific language governing permissions and limitations
18 | # under the License.
19 | # ----------------------------------------------------------------------------
20 |
21 | # ----------------------------------------------------------------------------
22 | # Maven Start Up Batch script
23 | #
24 | # Required ENV vars:
25 | # ------------------
26 | # JAVA_HOME - location of a JDK home dir
27 | #
28 | # Optional ENV vars
29 | # -----------------
30 | # M2_HOME - location of maven2's installed home dir
31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven
32 | # e.g. to debug Maven itself, use
33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files
35 | # ----------------------------------------------------------------------------
36 |
37 | if [ -z "$MAVEN_SKIP_RC" ] ; then
38 |
39 | if [ -f /etc/mavenrc ] ; then
40 | . /etc/mavenrc
41 | fi
42 |
43 | if [ -f "$HOME/.mavenrc" ] ; then
44 | . "$HOME/.mavenrc"
45 | fi
46 |
47 | fi
48 |
49 | # OS specific support. $var _must_ be set to either true or false.
50 | cygwin=false;
51 | darwin=false;
52 | mingw=false
53 | case "`uname`" in
54 | CYGWIN*) cygwin=true ;;
55 | MINGW*) mingw=true;;
56 | Darwin*) darwin=true
57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
59 | if [ -z "$JAVA_HOME" ]; then
60 | if [ -x "/usr/libexec/java_home" ]; then
61 | export JAVA_HOME="`/usr/libexec/java_home`"
62 | else
63 | export JAVA_HOME="/Library/Java/Home"
64 | fi
65 | fi
66 | ;;
67 | esac
68 |
69 | if [ -z "$JAVA_HOME" ] ; then
70 | if [ -r /etc/gentoo-release ] ; then
71 | JAVA_HOME=`java-config --jre-home`
72 | fi
73 | fi
74 |
75 | if [ -z "$M2_HOME" ] ; then
76 | ## resolve links - $0 may be a link to maven's home
77 | PRG="$0"
78 |
79 | # need this for relative symlinks
80 | while [ -h "$PRG" ] ; do
81 | ls=`ls -ld "$PRG"`
82 | link=`expr "$ls" : '.*-> \(.*\)$'`
83 | if expr "$link" : '/.*' > /dev/null; then
84 | PRG="$link"
85 | else
86 | PRG="`dirname "$PRG"`/$link"
87 | fi
88 | done
89 |
90 | saveddir=`pwd`
91 |
92 | M2_HOME=`dirname "$PRG"`/..
93 |
94 | # make it fully qualified
95 | M2_HOME=`cd "$M2_HOME" && pwd`
96 |
97 | cd "$saveddir"
98 | # echo Using m2 at $M2_HOME
99 | fi
100 |
101 | # For Cygwin, ensure paths are in UNIX format before anything is touched
102 | if $cygwin ; then
103 | [ -n "$M2_HOME" ] &&
104 | M2_HOME=`cygpath --unix "$M2_HOME"`
105 | [ -n "$JAVA_HOME" ] &&
106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
107 | [ -n "$CLASSPATH" ] &&
108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
109 | fi
110 |
111 | # For Mingw, ensure paths are in UNIX format before anything is touched
112 | if $mingw ; then
113 | [ -n "$M2_HOME" ] &&
114 | M2_HOME="`(cd "$M2_HOME"; pwd)`"
115 | [ -n "$JAVA_HOME" ] &&
116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
117 | fi
118 |
119 | if [ -z "$JAVA_HOME" ]; then
120 | javaExecutable="`which javac`"
121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
122 | # readlink(1) is not available as standard on Solaris 10.
123 | readLink=`which readlink`
124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
125 | if $darwin ; then
126 | javaHome="`dirname \"$javaExecutable\"`"
127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
128 | else
129 | javaExecutable="`readlink -f \"$javaExecutable\"`"
130 | fi
131 | javaHome="`dirname \"$javaExecutable\"`"
132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
133 | JAVA_HOME="$javaHome"
134 | export JAVA_HOME
135 | fi
136 | fi
137 | fi
138 |
139 | if [ -z "$JAVACMD" ] ; then
140 | if [ -n "$JAVA_HOME" ] ; then
141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
142 | # IBM's JDK on AIX uses strange locations for the executables
143 | JAVACMD="$JAVA_HOME/jre/sh/java"
144 | else
145 | JAVACMD="$JAVA_HOME/bin/java"
146 | fi
147 | else
148 | JAVACMD="`which java`"
149 | fi
150 | fi
151 |
152 | if [ ! -x "$JAVACMD" ] ; then
153 | echo "Error: JAVA_HOME is not defined correctly." >&2
154 | echo " We cannot execute $JAVACMD" >&2
155 | exit 1
156 | fi
157 |
158 | if [ -z "$JAVA_HOME" ] ; then
159 | echo "Warning: JAVA_HOME environment variable is not set."
160 | fi
161 |
162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
163 |
164 | # traverses directory structure from process work directory to filesystem root
165 | # first directory with .mvn subdirectory is considered project base directory
166 | find_maven_basedir() {
167 |
168 | if [ -z "$1" ]
169 | then
170 | echo "Path not specified to find_maven_basedir"
171 | return 1
172 | fi
173 |
174 | basedir="$1"
175 | wdir="$1"
176 | while [ "$wdir" != '/' ] ; do
177 | if [ -d "$wdir"/.mvn ] ; then
178 | basedir=$wdir
179 | break
180 | fi
181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
182 | if [ -d "${wdir}" ]; then
183 | wdir=`cd "$wdir/.."; pwd`
184 | fi
185 | # end of workaround
186 | done
187 | echo "${basedir}"
188 | }
189 |
190 | # concatenates all lines of a file
191 | concat_lines() {
192 | if [ -f "$1" ]; then
193 | echo "$(tr -s '\n' ' ' < "$1")"
194 | fi
195 | }
196 |
197 | BASE_DIR=`find_maven_basedir "$(pwd)"`
198 | if [ -z "$BASE_DIR" ]; then
199 | exit 1;
200 | fi
201 |
202 | ##########################################################################################
203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
204 | # This allows using the maven wrapper in projects that prohibit checking in binary data.
205 | ##########################################################################################
206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
207 | if [ "$MVNW_VERBOSE" = true ]; then
208 | echo "Found .mvn/wrapper/maven-wrapper.jar"
209 | fi
210 | else
211 | if [ "$MVNW_VERBOSE" = true ]; then
212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
213 | fi
214 | if [ -n "$MVNW_REPOURL" ]; then
215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
216 | else
217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
218 | fi
219 | while IFS="=" read key value; do
220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
221 | esac
222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
223 | if [ "$MVNW_VERBOSE" = true ]; then
224 | echo "Downloading from: $jarUrl"
225 | fi
226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
227 | if $cygwin; then
228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
229 | fi
230 |
231 | if command -v wget > /dev/null; then
232 | if [ "$MVNW_VERBOSE" = true ]; then
233 | echo "Found wget ... using wget"
234 | fi
235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
236 | wget "$jarUrl" -O "$wrapperJarPath"
237 | else
238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
239 | fi
240 | elif command -v curl > /dev/null; then
241 | if [ "$MVNW_VERBOSE" = true ]; then
242 | echo "Found curl ... using curl"
243 | fi
244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
245 | curl -o "$wrapperJarPath" "$jarUrl" -f
246 | else
247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
248 | fi
249 |
250 | else
251 | if [ "$MVNW_VERBOSE" = true ]; then
252 | echo "Falling back to using Java to download"
253 | fi
254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
255 | # For Cygwin, switch paths to Windows format before running javac
256 | if $cygwin; then
257 | javaClass=`cygpath --path --windows "$javaClass"`
258 | fi
259 | if [ -e "$javaClass" ]; then
260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
261 | if [ "$MVNW_VERBOSE" = true ]; then
262 | echo " - Compiling MavenWrapperDownloader.java ..."
263 | fi
264 | # Compiling the Java class
265 | ("$JAVA_HOME/bin/javac" "$javaClass")
266 | fi
267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
268 | # Running the downloader
269 | if [ "$MVNW_VERBOSE" = true ]; then
270 | echo " - Running MavenWrapperDownloader.java ..."
271 | fi
272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
273 | fi
274 | fi
275 | fi
276 | fi
277 | ##########################################################################################
278 | # End of extension
279 | ##########################################################################################
280 |
281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
282 | if [ "$MVNW_VERBOSE" = true ]; then
283 | echo $MAVEN_PROJECTBASEDIR
284 | fi
285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
286 |
287 | # For Cygwin, switch paths to Windows format before running java
288 | if $cygwin; then
289 | [ -n "$M2_HOME" ] &&
290 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
291 | [ -n "$JAVA_HOME" ] &&
292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
293 | [ -n "$CLASSPATH" ] &&
294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
295 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
297 | fi
298 |
299 | # Provide a "standardized" way to retrieve the CLI args that will
300 | # work with both Windows and non-Windows executions.
301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
302 | export MAVEN_CMD_LINE_ARGS
303 |
304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
305 |
306 | exec "$JAVACMD" \
307 | $MAVEN_OPTS \
308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
311 |
--------------------------------------------------------------------------------
/examples/jdempotent-couchbase-example/mvnw:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # ----------------------------------------------------------------------------
3 | # Licensed to the Apache Software Foundation (ASF) under one
4 | # or more contributor license agreements. See the NOTICE file
5 | # distributed with this work for additional information
6 | # regarding copyright ownership. The ASF licenses this file
7 | # to you under the Apache License, Version 2.0 (the
8 | # "License"); you may not use this file except in compliance
9 | # with the License. You may obtain a copy of the License at
10 | #
11 | # https://www.apache.org/licenses/LICENSE-2.0
12 | #
13 | # Unless required by applicable law or agreed to in writing,
14 | # software distributed under the License is distributed on an
15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 | # KIND, either express or implied. See the License for the
17 | # specific language governing permissions and limitations
18 | # under the License.
19 | # ----------------------------------------------------------------------------
20 |
21 | # ----------------------------------------------------------------------------
22 | # Maven Start Up Batch script
23 | #
24 | # Required ENV vars:
25 | # ------------------
26 | # JAVA_HOME - location of a JDK home dir
27 | #
28 | # Optional ENV vars
29 | # -----------------
30 | # M2_HOME - location of maven2's installed home dir
31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven
32 | # e.g. to debug Maven itself, use
33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files
35 | # ----------------------------------------------------------------------------
36 |
37 | if [ -z "$MAVEN_SKIP_RC" ] ; then
38 |
39 | if [ -f /etc/mavenrc ] ; then
40 | . /etc/mavenrc
41 | fi
42 |
43 | if [ -f "$HOME/.mavenrc" ] ; then
44 | . "$HOME/.mavenrc"
45 | fi
46 |
47 | fi
48 |
49 | # OS specific support. $var _must_ be set to either true or false.
50 | cygwin=false;
51 | darwin=false;
52 | mingw=false
53 | case "`uname`" in
54 | CYGWIN*) cygwin=true ;;
55 | MINGW*) mingw=true;;
56 | Darwin*) darwin=true
57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
59 | if [ -z "$JAVA_HOME" ]; then
60 | if [ -x "/usr/libexec/java_home" ]; then
61 | export JAVA_HOME="`/usr/libexec/java_home`"
62 | else
63 | export JAVA_HOME="/Library/Java/Home"
64 | fi
65 | fi
66 | ;;
67 | esac
68 |
69 | if [ -z "$JAVA_HOME" ] ; then
70 | if [ -r /etc/gentoo-release ] ; then
71 | JAVA_HOME=`java-config --jre-home`
72 | fi
73 | fi
74 |
75 | if [ -z "$M2_HOME" ] ; then
76 | ## resolve links - $0 may be a link to maven's home
77 | PRG="$0"
78 |
79 | # need this for relative symlinks
80 | while [ -h "$PRG" ] ; do
81 | ls=`ls -ld "$PRG"`
82 | link=`expr "$ls" : '.*-> \(.*\)$'`
83 | if expr "$link" : '/.*' > /dev/null; then
84 | PRG="$link"
85 | else
86 | PRG="`dirname "$PRG"`/$link"
87 | fi
88 | done
89 |
90 | saveddir=`pwd`
91 |
92 | M2_HOME=`dirname "$PRG"`/..
93 |
94 | # make it fully qualified
95 | M2_HOME=`cd "$M2_HOME" && pwd`
96 |
97 | cd "$saveddir"
98 | # echo Using m2 at $M2_HOME
99 | fi
100 |
101 | # For Cygwin, ensure paths are in UNIX format before anything is touched
102 | if $cygwin ; then
103 | [ -n "$M2_HOME" ] &&
104 | M2_HOME=`cygpath --unix "$M2_HOME"`
105 | [ -n "$JAVA_HOME" ] &&
106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
107 | [ -n "$CLASSPATH" ] &&
108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
109 | fi
110 |
111 | # For Mingw, ensure paths are in UNIX format before anything is touched
112 | if $mingw ; then
113 | [ -n "$M2_HOME" ] &&
114 | M2_HOME="`(cd "$M2_HOME"; pwd)`"
115 | [ -n "$JAVA_HOME" ] &&
116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
117 | fi
118 |
119 | if [ -z "$JAVA_HOME" ]; then
120 | javaExecutable="`which javac`"
121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
122 | # readlink(1) is not available as standard on Solaris 10.
123 | readLink=`which readlink`
124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
125 | if $darwin ; then
126 | javaHome="`dirname \"$javaExecutable\"`"
127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
128 | else
129 | javaExecutable="`readlink -f \"$javaExecutable\"`"
130 | fi
131 | javaHome="`dirname \"$javaExecutable\"`"
132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
133 | JAVA_HOME="$javaHome"
134 | export JAVA_HOME
135 | fi
136 | fi
137 | fi
138 |
139 | if [ -z "$JAVACMD" ] ; then
140 | if [ -n "$JAVA_HOME" ] ; then
141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
142 | # IBM's JDK on AIX uses strange locations for the executables
143 | JAVACMD="$JAVA_HOME/jre/sh/java"
144 | else
145 | JAVACMD="$JAVA_HOME/bin/java"
146 | fi
147 | else
148 | JAVACMD="`which java`"
149 | fi
150 | fi
151 |
152 | if [ ! -x "$JAVACMD" ] ; then
153 | echo "Error: JAVA_HOME is not defined correctly." >&2
154 | echo " We cannot execute $JAVACMD" >&2
155 | exit 1
156 | fi
157 |
158 | if [ -z "$JAVA_HOME" ] ; then
159 | echo "Warning: JAVA_HOME environment variable is not set."
160 | fi
161 |
162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
163 |
164 | # traverses directory structure from process work directory to filesystem root
165 | # first directory with .mvn subdirectory is considered project base directory
166 | find_maven_basedir() {
167 |
168 | if [ -z "$1" ]
169 | then
170 | echo "Path not specified to find_maven_basedir"
171 | return 1
172 | fi
173 |
174 | basedir="$1"
175 | wdir="$1"
176 | while [ "$wdir" != '/' ] ; do
177 | if [ -d "$wdir"/.mvn ] ; then
178 | basedir=$wdir
179 | break
180 | fi
181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
182 | if [ -d "${wdir}" ]; then
183 | wdir=`cd "$wdir/.."; pwd`
184 | fi
185 | # end of workaround
186 | done
187 | echo "${basedir}"
188 | }
189 |
190 | # concatenates all lines of a file
191 | concat_lines() {
192 | if [ -f "$1" ]; then
193 | echo "$(tr -s '\n' ' ' < "$1")"
194 | fi
195 | }
196 |
197 | BASE_DIR=`find_maven_basedir "$(pwd)"`
198 | if [ -z "$BASE_DIR" ]; then
199 | exit 1;
200 | fi
201 |
202 | ##########################################################################################
203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
204 | # This allows using the maven wrapper in projects that prohibit checking in binary data.
205 | ##########################################################################################
206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
207 | if [ "$MVNW_VERBOSE" = true ]; then
208 | echo "Found .mvn/wrapper/maven-wrapper.jar"
209 | fi
210 | else
211 | if [ "$MVNW_VERBOSE" = true ]; then
212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
213 | fi
214 | if [ -n "$MVNW_REPOURL" ]; then
215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
216 | else
217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
218 | fi
219 | while IFS="=" read key value; do
220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
221 | esac
222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
223 | if [ "$MVNW_VERBOSE" = true ]; then
224 | echo "Downloading from: $jarUrl"
225 | fi
226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
227 | if $cygwin; then
228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
229 | fi
230 |
231 | if command -v wget > /dev/null; then
232 | if [ "$MVNW_VERBOSE" = true ]; then
233 | echo "Found wget ... using wget"
234 | fi
235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
236 | wget "$jarUrl" -O "$wrapperJarPath"
237 | else
238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
239 | fi
240 | elif command -v curl > /dev/null; then
241 | if [ "$MVNW_VERBOSE" = true ]; then
242 | echo "Found curl ... using curl"
243 | fi
244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
245 | curl -o "$wrapperJarPath" "$jarUrl" -f
246 | else
247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
248 | fi
249 |
250 | else
251 | if [ "$MVNW_VERBOSE" = true ]; then
252 | echo "Falling back to using Java to download"
253 | fi
254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
255 | # For Cygwin, switch paths to Windows format before running javac
256 | if $cygwin; then
257 | javaClass=`cygpath --path --windows "$javaClass"`
258 | fi
259 | if [ -e "$javaClass" ]; then
260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
261 | if [ "$MVNW_VERBOSE" = true ]; then
262 | echo " - Compiling MavenWrapperDownloader.java ..."
263 | fi
264 | # Compiling the Java class
265 | ("$JAVA_HOME/bin/javac" "$javaClass")
266 | fi
267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
268 | # Running the downloader
269 | if [ "$MVNW_VERBOSE" = true ]; then
270 | echo " - Running MavenWrapperDownloader.java ..."
271 | fi
272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
273 | fi
274 | fi
275 | fi
276 | fi
277 | ##########################################################################################
278 | # End of extension
279 | ##########################################################################################
280 |
281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
282 | if [ "$MVNW_VERBOSE" = true ]; then
283 | echo $MAVEN_PROJECTBASEDIR
284 | fi
285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
286 |
287 | # For Cygwin, switch paths to Windows format before running java
288 | if $cygwin; then
289 | [ -n "$M2_HOME" ] &&
290 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
291 | [ -n "$JAVA_HOME" ] &&
292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
293 | [ -n "$CLASSPATH" ] &&
294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
295 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
297 | fi
298 |
299 | # Provide a "standardized" way to retrieve the CLI args that will
300 | # work with both Windows and non-Windows executions.
301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
302 | export MAVEN_CMD_LINE_ARGS
303 |
304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
305 |
306 | exec "$JAVACMD" \
307 | $MAVEN_OPTS \
308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
311 |
--------------------------------------------------------------------------------