-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathonly-mvnw
More file actions
executable file
·1167 lines (1041 loc) · 46.2 KB
/
Copy pathonly-mvnw
File metadata and controls
executable file
·1167 lines (1041 loc) · 46.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version @@project.version@@
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# MVNW_SKIP_JDK - true: skip JDK installation and management (use system JDK)
#
# JDK Management ENV vars (override maven-wrapper.properties)
# -----------------------------------------------------------
# MVNW_JDK_VERSION - JDK version to download and use (e.g., 17, 21, 17.0.14)
# MVNW_JDK_DISTRIBUTION - JDK distribution name (e.g., temurin, corretto, zulu)
# MVNW_JDK_DISTRIBUTION_URL - Direct URL to JDK archive (overrides version/distribution)
# MVNW_JDK_SHA256_SUM - SHA-256 checksum for JDK archive verification
# MVNW_JDK_UPDATE_POLICY - Update policy (never, daily, weekly, monthly, always, interval:X)
# MVNW_ALWAYS_DOWNLOAD_JDK - Force re-download of JDK (true/false)
# MVNW_TOOLCHAIN_JDK_VERSION - Toolchain JDK version (e.g., 11, 8)
# MVNW_TOOLCHAIN_JDK_DISTRIBUTION - Toolchain JDK distribution name
# MVNW_TOOLCHAIN_JDK_DISTRIBUTION_URL - Direct URL to toolchain JDK archive
# MVNW_TOOLCHAIN_JDK_SHA256_SUM - SHA-256 checksum for toolchain JDK archive
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}" >&2; }
# JDK management functions
# Retry HTTP request with exponential backoff for 5xx errors
retry_http_request() {
url="$1"
max_attempts="${2:-3}"
base_delay="${3:-2}"
attempt=1
while [ "$attempt" -le "$max_attempts" ]; do
if command -v curl >/dev/null; then
# Use curl with status code capture
temp_response="$(mktemp)"
http_status="$(curl -s -w "%{http_code}" -o "$temp_response" "$url" 2>/dev/null)"
if [ "$http_status" = "200" ]; then
cat "$temp_response"
rm -f "$temp_response" 2>/dev/null || true
return 0
elif [ "$http_status" -ge 500 ] && [ "$http_status" -lt 600 ] && [ "$attempt" -lt "$max_attempts" ]; then
# 5xx error, retry with exponential backoff and jitter
delay=$(calculate_retry_delay "$attempt" "$base_delay")
verbose "HTTP $http_status received, retrying in ${delay}s (attempt $attempt/$max_attempts)"
sleep "$delay"
else
# Non-retryable error or max attempts reached
rm -f "$temp_response" 2>/dev/null || true
echo "HTTP_ERROR:$http_status" >&2
return 1
fi
rm -f "$temp_response" 2>/dev/null || true
elif command -v wget >/dev/null; then
# Use wget with status code extraction from server response
temp_response="$(mktemp)"
temp_headers="$(mktemp)"
# wget with server response headers to extract status code
if wget --server-response -q -O "$temp_response" "$url" 2>"$temp_headers"; then
# Success - return the response
cat "$temp_response"
rm -f "$temp_response" "$temp_headers" 2>/dev/null || true
return 0
else
# Extract HTTP status code from wget's server response output
http_status="$(grep -o 'HTTP/[0-9.]\+ [0-9]\+' "$temp_headers" 2>/dev/null | tail -1 | awk '{print $2}')"
if [ -n "$http_status" ] && [ "$http_status" -ge 500 ] && [ "$http_status" -lt 600 ] && [ "$attempt" -lt "$max_attempts" ]; then
# 5xx error, retry with exponential backoff and jitter
delay=$(calculate_retry_delay "$attempt" "$base_delay")
verbose "HTTP $http_status received, retrying in ${delay}s (attempt $attempt/$max_attempts)"
sleep "$delay"
else
# Non-retryable error or max attempts reached
rm -f "$temp_response" "$temp_headers" 2>/dev/null || true
if [ -n "$http_status" ]; then
echo "HTTP_ERROR:$http_status" >&2
else
echo "HTTP_ERROR:unknown" >&2
fi
return 1
fi
rm -f "$temp_response" "$temp_headers" 2>/dev/null || true
fi
elif command -v busybox >/dev/null && busybox wget --help >/dev/null 2>&1; then
# Busybox wget fallback (limited functionality)
if busybox wget -q -O - "$url" 2>/dev/null; then
return 0
elif [ "$attempt" -lt "$max_attempts" ]; then
# Exponential backoff with jitter
delay=$(calculate_retry_delay "$attempt" "$base_delay")
verbose "Request failed, retrying in ${delay}s (attempt $attempt/$max_attempts)"
sleep "$delay"
else
echo "HTTP_ERROR:unknown" >&2
return 1
fi
else
echo "HTTP_ERROR:no_client" >&2
return 1
fi
attempt=$((attempt + 1))
done
return 1
}
# Calculate exponential backoff delay with jitter (POSIX-compliant)
# Usage: calculate_retry_delay <attempt_number> <base_delay>
# Returns: delay in seconds with exponential backoff and 0-20% jitter
calculate_retry_delay() {
attempt="$1"
base_delay="${2:-2}"
# Calculate exponential backoff: base_delay * 2^(attempt-1)
delay_calc="$base_delay"
i=1
while [ "$i" -lt "$attempt" ]; do
delay_calc=$((delay_calc * 2))
i=$((i + 1))
done
# Generate POSIX-compliant random jitter (0-20%)
if [ -r /dev/urandom ]; then
# Use /dev/urandom if available (most Unix systems)
jitter_percent=$(od -An -N1 -tu1 /dev/urandom 2>/dev/null | awk '{print $1 % 21}')
else
# Fallback: use current time and process ID for pseudo-randomness
jitter_percent=$((($(date +%s) + $$) % 21))
fi
# Apply jitter to delay
jitter=$((delay_calc * jitter_percent / 100))
final_delay=$((delay_calc + jitter))
echo "$final_delay"
}
# Download file with retry logic and exponential backoff
download_file_with_retry() {
url="$1"
output_file="$2"
max_attempts="${3:-3}"
base_delay="${4:-2}"
attempt=1
last_http_status=""
while [ "$attempt" -le "$max_attempts" ]; do
if command -v curl >/dev/null; then
# Use curl with status code capture
http_status="$(curl -s -w "%{http_code}" -L -o "$output_file" "$url" 2>/dev/null)"
last_http_status="$http_status"
if [ "$http_status" = "200" ]; then
return 0
elif [ "$http_status" -ge 500 ] && [ "$http_status" -lt 600 ] && [ "$attempt" -lt "$max_attempts" ]; then
# 5xx error, retry with exponential backoff and jitter
delay=$(calculate_retry_delay "$attempt" "$base_delay")
verbose "HTTP $http_status received, retrying download in ${delay}s (attempt $attempt/$max_attempts)"
sleep "$delay"
else
# Non-retryable error or max attempts reached
echo "HTTP_ERROR:$http_status" >&2
return 1
fi
elif command -v wget >/dev/null; then
# Use wget with status code extraction
temp_headers="$(mktemp)"
if wget --server-response -q -O "$output_file" "$url" 2>"$temp_headers"; then
rm -f "$temp_headers" 2>/dev/null || true
return 0
else
# Extract HTTP status code from wget's server response output
http_status="$(grep -o 'HTTP/[0-9.]\+ [0-9]\+' "$temp_headers" 2>/dev/null | tail -1 | awk '{print $2}')"
last_http_status="$http_status"
if [ -n "$http_status" ] && [ "$http_status" -ge 500 ] && [ "$http_status" -lt 600 ] && [ "$attempt" -lt "$max_attempts" ]; then
# 5xx error, retry with exponential backoff and jitter
delay=$(calculate_retry_delay "$attempt" "$base_delay")
verbose "HTTP $http_status received, retrying download in ${delay}s (attempt $attempt/$max_attempts)"
sleep "$delay"
else
# Non-retryable error or max attempts reached
rm -f "$temp_headers" 2>/dev/null || true
if [ -n "$http_status" ]; then
echo "HTTP_ERROR:$http_status" >&2
else
echo "HTTP_ERROR:unknown" >&2
fi
return 1
fi
rm -f "$temp_headers" 2>/dev/null || true
fi
elif command -v busybox >/dev/null && busybox wget --help >/dev/null 2>&1; then
# Busybox wget fallback (limited functionality)
if busybox wget -q -O "$output_file" "$url" 2>/dev/null; then
return 0
elif [ "$attempt" -lt "$max_attempts" ]; then
# Exponential backoff with jitter
delay=$(calculate_retry_delay "$attempt" "$base_delay")
verbose "Download failed, retrying in ${delay}s (attempt $attempt/$max_attempts)"
sleep "$delay"
else
last_http_status="unknown"
echo "HTTP_ERROR:unknown" >&2
return 1
fi
else
last_http_status="no_client"
echo "HTTP_ERROR:no_client" >&2
return 1
fi
attempt=$((attempt + 1))
done
# If we get here, all attempts failed
if [ -n "$last_http_status" ]; then
echo "HTTP_ERROR:$last_http_status" >&2
else
echo "HTTP_ERROR:unknown" >&2
fi
return 1
}
detect_platform() {
case "$(uname)" in
Darwin*) echo "macos" ;;
CYGWIN* | MINGW*) echo "windows" ;;
*) echo "linux" ;;
esac
}
detect_architecture() {
case "$(uname -m)" in
x86_64 | amd64) echo "x64" ;;
aarch64 | arm64) echo "aarch64" ;;
i386 | i686) echo "x86" ;;
*) echo "x64" ;; # default fallback
esac
}
# Disco API constants
DISCO_API_BASE_URL="https://api.foojay.io/disco/v3.0"
# Validate distribution name against known Disco API distributions
validate_distribution() {
distribution="$1"
case "$distribution" in
aoj | aoj_openj9 | bisheng | corretto | debian | dragonwell | gluon_graalvm | graalvm | graalvm_ce11 | graalvm_ce16 | graalvm_ce17 | graalvm_ce19 | graalvm_ce20 | graalvm_ce8 | graalvm_community | jetbrains | kona | liberica | liberica_native | mandrel | microsoft | ojdk_build | openlogic | oracle | oracle_open_jdk | redhat | sap_machine | semeru | semeru_certified | temurin | trava | zulu | zulu_prime)
return 0 # Valid distribution
;;
*)
return 1 # Invalid distribution
;;
esac
}
# Display available distributions
show_available_distributions() {
echo "Available JDK distributions:" >&2
echo " - temurin (Eclipse Adoptium - default)" >&2
echo " - corretto (Amazon)" >&2
echo " - zulu (Azul)" >&2
echo " - liberica (BellSoft)" >&2
echo " - oracle_open_jdk (Oracle OpenJDK)" >&2
echo " - microsoft (Microsoft)" >&2
echo " - semeru (IBM)" >&2
echo " - graalvm_ce11 (GraalVM CE 11)" >&2
echo " - graalvm_ce17 (GraalVM CE 17)" >&2
echo " - sap_machine (SAP)" >&2
echo " - dragonwell (Alibaba)" >&2
echo " - jetbrains (JetBrains Runtime)" >&2
echo " - bisheng (Huawei)" >&2
echo " - kona (Tencent)" >&2
echo " - mandrel (Red Hat)" >&2
echo " - openlogic (OpenLogic)" >&2
echo "" >&2
echo "For a complete list, see: ${DISCO_API_BASE_URL}/distributions" >&2
}
resolve_jdk_url() {
_resolve_version="$1"
_resolve_distribution="${2:-temurin}"
# Validate distribution name
if ! validate_distribution "$_resolve_distribution"; then
echo "ERROR: Unknown JDK distribution '$_resolve_distribution'." >&2
echo "" >&2
show_available_distributions
echo "" >&2
echo "To use a different distribution, set jdkDistribution in maven-wrapper.properties:" >&2
echo " jdkDistribution=temurin" >&2
echo " jdkDistribution=corretto" >&2
echo " jdkDistribution=zulu" >&2
echo "" >&2
echo "Alternatively, specify an exact JDK URL with jdkDistributionUrl." >&2
die "Invalid JDK distribution: $_resolve_distribution"
fi
# Resolve version if it's a major version
_resolved_version="$(resolve_jdk_version "$_resolve_version" "$_resolve_distribution")"
# Detect platform and architecture for Disco API
_resolve_platform="$(detect_platform)"
_resolve_architecture="$(detect_architecture)"
# Determine archive type based on platform
case "$_resolve_platform" in
windows) _resolve_archive_type="zip" ;;
*) _resolve_archive_type="tar.gz" ;;
esac
# For URL resolution, always use the original major version if available
# This avoids issues with the Foojay API not properly filtering by specific java_version
if echo "$_resolve_version" | grep -q '^[0-9]\+$'; then
# Original input was a major version, use it directly
_resolve_version_param="jdk_version=${_resolve_version}"
else
# Original input was a specific version, extract major version
_resolve_major_version="$(echo "$_resolve_version" | sed 's/\([0-9]\+\).*/\1/')"
_resolve_version_param="jdk_version=${_resolve_major_version}"
fi
# Build Disco API URL for package information (more reliable than direct URI)
# Only get directly downloadable packages to avoid redirect-only entries
# Add lib_c_type=glibc only for Linux to prefer glibc over musl
_resolve_lib_c_param=""
if [ "${_resolve_platform}" = "linux" ]; then
_resolve_lib_c_param="&lib_c_type=glibc"
fi
_resolve_disco_api_url="${DISCO_API_BASE_URL}/packages?distro=${_resolve_distribution}&javafx_bundled=false&archive_type=${_resolve_archive_type}&operating_system=${_resolve_platform}&package_type=jdk&${_resolve_version_param}&architecture=${_resolve_architecture}&latest=available&release_status=ga${_resolve_lib_c_param}&directly_downloadable=true&include_versions=false"
verbose "Resolving JDK download URL from Disco API: $_resolve_disco_api_url"
# Make HTTP request to Disco API with retry logic
_resolve_http_status=""
_resolve_api_response="$(retry_http_request "$_resolve_disco_api_url" 3 2 2>/dev/null)"
_resolve_retry_result=$?
if [ $_resolve_retry_result -ne 0 ]; then
# Extract HTTP status from stderr if available
_resolve_http_status="$(retry_http_request "$_resolve_disco_api_url" 1 1 2>&1 >/dev/null | sed -n 's/HTTP_ERROR://p')"
_resolve_api_response=""
verbose "Disco API returned HTTP status: $_resolve_http_status"
# Check if it's a "no client" error
if [ "$_resolve_http_status" = "no_client" ]; then
echo "ERROR: Cannot download JDK - no HTTP client available (curl, wget, or busybox wget required)" >&2
echo "" >&2
echo "To fix this issue:" >&2
echo "1. Install curl or wget on your system" >&2
echo "2. Set MVNW_SKIP_JDK=true to use system JDK instead" >&2
die "Cannot download JDK: curl, wget, or busybox wget required"
fi
fi
if [ -z "$_resolve_api_response" ]; then
echo "ERROR: Failed to get JDK package information from Disco API" >&2
if [ -n "$_resolve_http_status" ] && [ "$_resolve_http_status" != "200" ] && [ "$_resolve_http_status" != "unknown" ]; then
echo "HTTP Status: $_resolve_http_status" >&2
if [ "$_resolve_http_status" = "503" ]; then
echo "The Disco API is temporarily unavailable (Service Unavailable)" >&2
echo "This is likely a temporary issue with the Foojay Disco API service" >&2
elif [ "$_resolve_http_status" = "429" ]; then
echo "Rate limited by Disco API (Too Many Requests)" >&2
elif [ "$_resolve_http_status" = "404" ]; then
echo "JDK package not found (Not Found)" >&2
else
echo "Disco API returned error status: $_resolve_http_status" >&2
fi
elif [ "$_resolve_http_status" = "unknown" ]; then
echo "Unable to determine HTTP status (network or parsing error)" >&2
fi
echo "Version: $_resolved_version, Distribution: $_resolve_distribution" >&2
echo "Platform: $_resolve_platform $_resolve_architecture" >&2
echo "API URL: $_resolve_disco_api_url" >&2
echo "" >&2
echo "This could be due to:" >&2
echo "1. Network connectivity issues" >&2
echo "2. Disco API being temporarily unavailable (HTTP 503)" >&2
echo "3. Rate limiting (HTTP 429)" >&2
echo "4. Invalid JDK version or distribution combination (HTTP 404)" >&2
echo "" >&2
echo "To fix this issue:" >&2
echo "1. Check your internet connection" >&2
echo "2. Wait a few minutes and try again (if HTTP 503/429)" >&2
echo "3. Use a direct JDK URL with jdkDistributionUrl in maven-wrapper.properties" >&2
echo "4. Set MVNW_SKIP_JDK=true to use system JDK" >&2
echo "5. Try a different JDK distribution (temurin, corretto, zulu, etc.)" >&2
die "Failed to get JDK package information for version $_resolved_version, distribution $_resolve_distribution on $_resolve_platform $_resolve_architecture"
fi
# Extract the download redirect URL from the JSON response
_resolve_redirect_url="$(echo "$_resolve_api_response" | sed -n 's/.*"pkg_download_redirect":"\([^"]*\)".*/\1/p' | head -1)"
if [ -z "$_resolve_redirect_url" ]; then
echo "ERROR: Failed to extract JDK download URL from Disco API response" >&2
echo "Version: $_resolved_version, Distribution: $_resolve_distribution" >&2
echo "Platform: $_resolve_platform $_resolve_architecture" >&2
echo "" >&2
echo "This could be due to:" >&2
echo "1. Invalid API response format" >&2
echo "2. No matching JDK package available" >&2
echo "3. Disco API changes" >&2
echo "" >&2
echo "To fix this issue:" >&2
echo "1. Use a direct JDK URL with jdkDistributionUrl in maven-wrapper.properties" >&2
echo "2. Set MVNW_SKIP_JDK=true to use system JDK" >&2
echo "3. Try a different JDK distribution or version" >&2
die "Failed to extract JDK download URL for version $_resolved_version, distribution $_resolve_distribution on $_resolve_platform $_resolve_architecture"
fi
# Follow the redirect to get the actual download URL
if command -v curl >/dev/null; then
_resolve_download_url="$(curl --retry 5 --retry-delay 10 -s -I "$_resolve_redirect_url" 2>/dev/null | grep -i '^location:' | cut -d' ' -f2- | tr -d '\r\n')"
elif command -v wget >/dev/null; then
_resolve_download_url="$(wget --tries=5 --waitretry=10 --retry-connrefused -q -S -O /dev/null "$_resolve_redirect_url" 2>&1 | grep -i '^ location:' | cut -d' ' -f4- | tr -d '\r\n')"
elif command -v busybox >/dev/null && busybox wget --help >/dev/null 2>&1; then
_resolve_download_url="$(busybox wget --tries=5 -q -S -O /dev/null "$_resolve_redirect_url" 2>&1 | grep -i '^ location:' | cut -d' ' -f4- | tr -d '\r\n')"
else
# Fallback to using the redirect URL directly
_resolve_download_url="$_resolve_redirect_url"
fi
if [ -z "$_resolve_download_url" ]; then
# Fallback to using the redirect URL directly
_resolve_download_url="$_resolve_redirect_url"
fi
echo "$_resolve_download_url"
}
get_cache_max_age_seconds() {
update_policy="${1:-daily}"
case "$update_policy" in
"never") echo "31536000" ;; # 1 year (effectively never)
"daily") echo "86400" ;; # 24 hours
"always") echo "0" ;; # Always expired
"weekly") echo "604800" ;; # 7 days
"monthly") echo "2592000" ;; # 30 days
interval:*)
# Extract minutes from interval:X format
minutes="$(echo "$update_policy" | sed 's/interval://')"
if echo "$minutes" | grep -q '^[0-9]\+$'; then
echo $((minutes * 60))
else
verbose "Invalid interval format: $update_policy, using daily"
echo "86400"
fi
;;
*)
verbose "Unknown update policy: $update_policy, using daily"
echo "86400"
;;
esac
}
resolve_jdk_version() {
version="$1"
distribution="$2"
# Handle major version resolution by querying Disco API
if echo "$version" | grep -q '^[0-9]\+$'; then
# This is a major version, get the latest from Disco API
latest_version="$(get_latest_version_from_disco "$version" "$distribution")"
if [ -n "$latest_version" ]; then
version="$latest_version"
else
# The detailed error message was already printed by get_latest_version_from_disco
die "Failed to resolve JDK version $version with distribution $distribution."
fi
fi
echo "$version"
}
get_latest_version_from_disco() {
major_version="$1"
distribution="$2"
# Detect platform and architecture for Disco API
platform="$(detect_platform)"
architecture="$(detect_architecture)"
# Get update policy and calculate cache max age
update_policy="${jdkUpdatePolicy:-daily}"
cache_max_age_seconds="$(get_cache_max_age_seconds "$update_policy")"
# Cache file location
cache_file="${MAVEN_USER_HOME}/wrapper/cache/jdk-${major_version}-${distribution}.cache"
cache_dir="$(dirname "$cache_file")"
# Check cache based on update policy
if [ -f "$cache_file" ] && [ "$cache_max_age_seconds" -gt 0 ]; then
if command -v stat >/dev/null; then
# Linux/macOS stat command
if stat -c %Y "$cache_file" >/dev/null 2>&1; then
cache_age="$(stat -c %Y "$cache_file")"
elif stat -f %m "$cache_file" >/dev/null 2>&1; then
cache_age="$(stat -f %m "$cache_file")"
fi
fi
if [ -n "$cache_age" ]; then
current_time="$(date +%s)"
age_seconds=$((current_time - cache_age))
if [ "$age_seconds" -lt "$cache_max_age_seconds" ]; then
cached_version="$(cat "$cache_file" 2>/dev/null)"
if [ -n "$cached_version" ]; then
verbose "Using cached JDK version (policy: $update_policy): ${major_version} -> ${cached_version}"
echo "$cached_version"
return 0
fi
else
verbose "Cache expired (policy: $update_policy, age: ${age_seconds}s, max: ${cache_max_age_seconds}s)"
fi
fi
elif [ "$update_policy" = "always" ]; then
verbose "Update policy 'always': skipping cache check"
fi
# Determine archive type based on platform
case "$platform" in
windows) archive_type="zip" ;;
*) archive_type="tar.gz" ;;
esac
# Query Disco API for the latest version
# Only get directly downloadable packages to avoid redirect-only entries
# Add lib_c_type=glibc only for Linux to prefer glibc over musl
lib_c_param=""
if [ "${platform}" = "linux" ]; then
lib_c_param="&lib_c_type=glibc"
fi
disco_api_url="${DISCO_API_BASE_URL}/packages?distro=${distribution}&package_type=jdk&jdk_version=${major_version}&operating_system=${platform}&architecture=${architecture}&archive_type=${archive_type}&latest=available&release_status=ga${lib_c_param}&directly_downloadable=true&include_versions=false"
verbose "Querying Disco API for JDK versions: $disco_api_url"
# Make HTTP request with retry logic for 5xx errors
http_status=""
api_response="$(retry_http_request "$disco_api_url" 3 2 2>/dev/null)"
retry_result=$?
if [ $retry_result -ne 0 ]; then
# Extract HTTP status from stderr if available
http_status="$(retry_http_request "$disco_api_url" 1 1 2>&1 >/dev/null | sed -n 's/HTTP_ERROR://p')"
api_response=""
verbose "Disco API request failed with status: $http_status"
# Check if it's a "no client" error
if [ "$http_status" = "no_client" ]; then
verbose "No HTTP client (curl/wget/busybox wget) available for Disco API"
echo "WARNING: Cannot resolve latest JDK version - no HTTP client available" >&2
echo "Using specified version as-is: $major_version" >&2
echo "To fix this, install curl or wget, or set MVNW_SKIP_JDK=true to use system JDK" >&2
return 1 # No HTTP client available
fi
fi
if [ -z "$api_response" ]; then
verbose "Disco API returned empty response for version resolution"
echo "WARNING: Cannot resolve latest JDK version from Disco API" >&2
if [ -n "$http_status" ] && [ "$http_status" != "200" ]; then
echo "HTTP Status: $http_status" >&2
if [ "$http_status" = "503" ]; then
echo "The Disco API is temporarily unavailable (Service Unavailable)" >&2
echo "This is likely a temporary issue with the Foojay Disco API service" >&2
elif [ "$http_status" = "429" ]; then
echo "Rate limited by Disco API (Too Many Requests)" >&2
fi
fi
echo "Using specified version as-is: $major_version" >&2
echo "API URL: $disco_api_url" >&2
echo "This could be due to network issues, API unavailability, or rate limiting" >&2
return 1 # API call failed
fi
# Extract the java_version from the JSON response (first result)
# Simple JSON parsing - look for "java_version":"..." pattern
latest_version="$(echo "$api_response" | sed -n 's/.*"java_version":"\([^"]*\)".*/\1/p' | head -1)"
if [ -n "$latest_version" ]; then
# Cache the result (unless policy is 'always')
if [ "$update_policy" != "always" ]; then
mkdir -p "$cache_dir"
echo "$latest_version" >"$cache_file" 2>/dev/null || true
fi
verbose "Resolved JDK version from Disco API (policy: $update_policy): ${major_version} -> ${latest_version}"
echo "$latest_version"
return 0
else
verbose "No matching JDK version found for ${major_version} with distribution ${distribution}"
# Special debug logging for known working combinations that fail
if [ "$major_version" = "17" ] && [ "$distribution" = "temurin" ]; then
echo "DEBUG: JDK 17 with Temurin should be available but was not found!" >&2
echo "DEBUG: This indicates a Disco API issue. Logging request details:" >&2
echo "DEBUG: API URL: $disco_api_url" >&2
echo "DEBUG: HTTP Status: $http_status" >&2
echo "DEBUG: Response length: ${#api_response} characters" >&2
if [ -n "$api_response" ] && [ "${#api_response}" -lt 1000 ]; then
echo "DEBUG: Full API response: $api_response" >&2
else
echo "DEBUG: API response (first 500 chars): $(echo "$api_response" | head -c 500)..." >&2
fi
echo "DEBUG: Expected pattern: \"java_version\":\"17.x.x\"" >&2
echo "DEBUG: Actual matches: $(echo "$api_response" | grep -o '"java_version":"[^"]*"' | head -3)" >&2
echo "" >&2
fi
# Show available alternatives for this major version
echo "ERROR: JDK ${major_version} is not available from distribution '${distribution}'." >&2
echo "" >&2
show_available_distributions
echo "" >&2
echo "To use a different distribution, set jdkDistribution in maven-wrapper.properties:" >&2
echo " jdkDistribution=temurin" >&2
echo " jdkDistribution=corretto" >&2
echo " jdkDistribution=zulu" >&2
echo "" >&2
echo "Alternatively, specify an exact JDK URL with jdkDistributionUrl." >&2
return 1 # No matching version found
fi
}
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
# Initialize JDK-related variables with empty defaults
jdkVersion=""
jdkDistribution=""
jdkDistributionUrl=""
jdkSha256Sum=""
jdkUpdatePolicy=""
alwaysDownloadJdk=""
toolchainJdkVersion=""
toolchainJdkDistribution=""
toolchainJdkDistributionUrl=""
toolchainJdkSha256Sum=""
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
# also parse JDK-related properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
jdkVersion) jdkVersion=$(trim "${value-}") ;;
jdkDistribution) jdkDistribution=$(trim "${value-}") ;;
jdkDistributionUrl) jdkDistributionUrl=$(trim "${value-}") ;;
jdkSha256Sum) jdkSha256Sum=$(trim "${value-}") ;;
jdkUpdatePolicy) jdkUpdatePolicy=$(trim "${value-}") ;;
alwaysDownloadJdk) alwaysDownloadJdk=$(trim "${value-}") ;;
toolchainJdkVersion) toolchainJdkVersion=$(trim "${value-}") ;;
toolchainJdkDistribution) toolchainJdkDistribution=$(trim "${value-}") ;;
toolchainJdkDistributionUrl) toolchainJdkDistributionUrl=$(trim "${value-}") ;;
toolchainJdkSha256Sum) toolchainJdkSha256Sum=$(trim "${value-}") ;;
esac
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
# Override JDK properties with environment variables if set
[ -z "${MVNW_JDK_VERSION-}" ] || jdkVersion="$MVNW_JDK_VERSION"
[ -z "${MVNW_JDK_DISTRIBUTION-}" ] || jdkDistribution="$MVNW_JDK_DISTRIBUTION"
[ -z "${MVNW_JDK_DISTRIBUTION_URL-}" ] || jdkDistributionUrl="$MVNW_JDK_DISTRIBUTION_URL"
[ -z "${MVNW_JDK_SHA256_SUM-}" ] || jdkSha256Sum="$MVNW_JDK_SHA256_SUM"
[ -z "${MVNW_JDK_UPDATE_POLICY-}" ] || jdkUpdatePolicy="$MVNW_JDK_UPDATE_POLICY"
[ -z "${MVNW_ALWAYS_DOWNLOAD_JDK-}" ] || alwaysDownloadJdk="$MVNW_ALWAYS_DOWNLOAD_JDK"
[ -z "${MVNW_TOOLCHAIN_JDK_VERSION-}" ] || toolchainJdkVersion="$MVNW_TOOLCHAIN_JDK_VERSION"
[ -z "${MVNW_TOOLCHAIN_JDK_DISTRIBUTION-}" ] || toolchainJdkDistribution="$MVNW_TOOLCHAIN_JDK_DISTRIBUTION"
[ -z "${MVNW_TOOLCHAIN_JDK_DISTRIBUTION_URL-}" ] || toolchainJdkDistributionUrl="$MVNW_TOOLCHAIN_JDK_DISTRIBUTION_URL"
[ -z "${MVNW_TOOLCHAIN_JDK_SHA256_SUM-}" ] || toolchainJdkSha256Sum="$MVNW_TOOLCHAIN_JDK_SHA256_SUM"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
# JDK management
install_jdk() {
version="$1"
distribution="${2:-temurin}"
url="$3"
checksum="$4"
# Check if JDK selection should be bypassed
if [ -n "${MVNW_SKIP_JDK-}" ]; then
verbose "Skipping JDK installation due to MVNW_SKIP_JDK environment variable"
return 0
fi
always_download="${5:-false}"
if [ -z "$version" ]; then
return 0 # No JDK version specified
fi
# Determine JDK installation directory
jdk_dir_name="jdk-${version}-${distribution}"
jdk_home="${MAVEN_USER_HOME}/wrapper/jdks/${jdk_dir_name}"
# Check if JDK already exists and we're not forcing re-download
if [ -d "$jdk_home" ] && [ "$always_download" != "true" ]; then
verbose "JDK $version already installed at $jdk_home"
export JAVA_HOME="$jdk_home"
return 0
fi
# Resolve JDK URL if not provided
if [ -z "$url" ]; then
url="$(resolve_jdk_url "$version" "$distribution")"
fi
verbose "Installing JDK $version from $url"
# Create JDK directory
mkdir -p "${jdk_home%/*}"
# Prepare temp dir for JDK download
if jdk_tmp_dir="$(mktemp -d)" && [ -d "$jdk_tmp_dir" ]; then
jdk_clean() { rm -rf -- "$jdk_tmp_dir"; }
trap jdk_clean HUP INT TERM EXIT
else
die "cannot create temp dir for JDK"
fi
# Download JDK
jdk_filename="${url##*/}"
jdk_file="$jdk_tmp_dir/$jdk_filename"
verbose "Downloading JDK to: $jdk_file"
# Download using retry strategy for better reliability
if [ -z "${MVNW_USERNAME-}" ]; then
verbose "Downloading JDK with retry strategy"
# Capture stderr to get HTTP status if download fails
download_stderr="$(download_file_with_retry "$url" "$jdk_file" 3 2 2>&1)"
download_result=$?
if [ $download_result -eq 0 ]; then
verbose "JDK download completed successfully"
else
# Extract HTTP status from stderr
http_status="$(echo "$download_stderr" | sed -n 's/HTTP_ERROR://p')"
if [ -n "$http_status" ] && [ "$http_status" != "unknown" ]; then
die "Failed to download JDK: HTTP $http_status from $url"
else
die "Failed to download JDK from $url (network error)"
fi
fi
elif set_java_home; then
# Fallback to authenticated download with Java
verbose "Downloading JDK with Java (authenticated)"
javaSource="$jdk_tmp_dir/JdkDownloader.java"
cat >"$javaSource" <<-END
public class JdkDownloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new JdkDownloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling JdkDownloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile JdkDownloader.java"
verbose " - Running JdkDownloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$jdk_tmp_dir")" JdkDownloader "$url" "$(native_path "$jdk_file")" || die "Failed to download JDK with Java"
else
die "Cannot download JDK: no HTTP client available and Java not found"
fi
# Verify checksum if provided
if [ -n "$checksum" ]; then
verbose "Verifying JDK checksum"
checksum_result=false
if command -v sha256sum >/dev/null; then
if echo "$checksum $jdk_file" | sha256sum -c - >/dev/null 2>&1; then
checksum_result=true
fi
elif command -v shasum >/dev/null; then
if echo "$checksum $jdk_file" | shasum -a 256 -c >/dev/null 2>&1; then
checksum_result=true
fi
else
echo "Warning: Checksum validation requested but neither 'sha256sum' or 'shasum' are available." >&2
fi
if [ "$checksum_result" = false ]; then
die "Error: Failed to validate JDK SHA-256 checksum"
fi
fi
# Extract JDK to temporary location first
jdk_extract_dir="$jdk_tmp_dir/extract"
mkdir -p "$jdk_extract_dir"
verbose "Extracting JDK archive to temporary location"
case "$jdk_filename" in
*.tar.gz | *.tgz)
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$jdk_file" -C "$jdk_extract_dir" || die "failed to extract JDK tar.gz"
;;
*.zip)
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$jdk_file" -d "$jdk_extract_dir" || die "failed to extract JDK zip"
else
die "Cannot extract JDK zip: unzip command not available"
fi
;;
*)
die "Unsupported JDK archive format: $jdk_filename"
;;
esac
# Find the actual JDK root directory (where bin/java exists)
verbose "Locating JDK root directory"
jdk_root_dir=""
# Debug: Show what was extracted
verbose "Contents of extraction directory:"
if [ "${MVNW_VERBOSE-}" = true ]; then
find "$jdk_extract_dir" -type f -name "java" 2>/dev/null | head -10 || true
echo "Directory structure (first 3 levels):"
find "$jdk_extract_dir" -maxdepth 3 -type d 2>/dev/null | head -20 || true
fi
# Search for bin/java in the extracted content (up to 4 levels deep to handle various archive structures)
# Use find to be more thorough than shell globbing
java_executable=$(find "$jdk_extract_dir" -name "java" -type f -path "*/bin/java" | head -1)
if [ -n "$java_executable" ]; then
# Get the JDK root directory (parent of bin directory)
jdk_root_dir=$(dirname "$(dirname "$java_executable")")
verbose "Found JDK root at: $jdk_root_dir"
else
# Fallback to original method for compatibility
for candidate in "$jdk_extract_dir" "$jdk_extract_dir"/* "$jdk_extract_dir"/*/* "$jdk_extract_dir"/*/*/* "$jdk_extract_dir"/*/*/*/*; do
if [ -f "$candidate/bin/java" ]; then
jdk_root_dir="$candidate"
verbose "Found JDK root at: $jdk_root_dir (fallback method)"
break
fi
done
fi
if [ -z "$jdk_root_dir" ]; then
echo "ERROR: Could not locate JDK root directory with bin/java in extracted archive"
echo "Extraction directory contents:"
find "$jdk_extract_dir" -type f -name "*java*" 2>/dev/null | head -10 || true
echo "Directory structure:"
find "$jdk_extract_dir" -maxdepth 4 -type d 2>/dev/null | head -30 || true
die "JDK extraction failed - no bin/java found"
fi
# Move the JDK root to the final location
verbose "Installing JDK to: $jdk_home"
mkdir -p "${jdk_home%/*}"
mv "$jdk_root_dir" "$jdk_home" || die "failed to move JDK to final location"
# Verify JDK installation
if [ ! -f "$jdk_home/bin/java" ]; then
die "JDK installation failed: java executable not found at $jdk_home/bin/java"
fi
verbose "JDK $version installed successfully at $jdk_home"
export JAVA_HOME="$jdk_home"
jdk_clean || :
}