-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathUtil.java
1792 lines (1651 loc) · 68.9 KB
/
Util.java
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
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.model.TaskListener;
import jenkins.util.MemoryReductionUtil;
import hudson.util.QuotedStringTokenizer;
import hudson.util.VariableResolver;
import jenkins.util.SystemProperties;
import jenkins.util.io.PathRemover;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.NullOutputStream;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.types.FileSet;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import java.io.*;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystemException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.CheckReturnValue;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.io.FileUtils;
import org.kohsuke.stapler.StaplerRequest;
/**
* Various utility methods that don't have more proper home.
*
* @author Kohsuke Kawaguchi
*/
public class Util {
// Constant number of milliseconds in various time units.
private static final long ONE_SECOND_MS = 1000;
private static final long ONE_MINUTE_MS = 60 * ONE_SECOND_MS;
private static final long ONE_HOUR_MS = 60 * ONE_MINUTE_MS;
private static final long ONE_DAY_MS = 24 * ONE_HOUR_MS;
private static final long ONE_MONTH_MS = 30 * ONE_DAY_MS;
private static final long ONE_YEAR_MS = 365 * ONE_DAY_MS;
/**
* Creates a filtered sublist.
* @since 1.176
*/
@NonNull
public static <T> List<T> filter( @NonNull Iterable<?> base, @NonNull Class<T> type ) {
List<T> r = new ArrayList<>();
for (Object i : base) {
if(type.isInstance(i))
r.add(type.cast(i));
}
return r;
}
/**
* Creates a filtered sublist.
*/
@NonNull
public static <T> List<T> filter( @NonNull List<?> base, @NonNull Class<T> type ) {
return filter((Iterable)base,type);
}
/**
* Pattern for capturing variables. Either $xyz, ${xyz} or ${a.b} but not $a.b, while ignoring "$$"
*/
private static final Pattern VARIABLE = Pattern.compile("\\$([A-Za-z0-9_]+|\\{[A-Za-z0-9_.]+\\}|\\$)");
/**
* Replaces the occurrence of '$key' by {@code properties.get('key')}.
*
* <p>
* Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
*
*/
@Nullable
public static String replaceMacro( @CheckForNull String s, @NonNull Map<String,String> properties) {
return replaceMacro(s, new VariableResolver.ByMap<>(properties));
}
/**
* Replaces the occurrence of '$key' by {@code resolver.get('key')}.
*
* <p>
* Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
*/
@Nullable
public static String replaceMacro(@CheckForNull String s, @NonNull VariableResolver<String> resolver) {
if (s == null) {
return null;
}
int idx=0;
while(true) {
Matcher m = VARIABLE.matcher(s);
if(!m.find(idx)) return s;
String key = m.group().substring(1);
// escape the dollar sign or get the key to resolve
String value;
if(key.charAt(0)=='$') {
value = "$";
} else {
if(key.charAt(0)=='{') key = key.substring(1,key.length()-1);
value = resolver.resolve(key);
}
if(value==null)
idx = m.end(); // skip this
else {
s = s.substring(0,m.start())+value+s.substring(m.end());
idx = m.start() + value.length();
}
}
}
/**
* Reads the entire contents of the text file at {@code logfile} into a
* string using the {@link Charset#defaultCharset() default charset} for
* decoding. If no such file exists, an empty string is returned.
* @param logfile The text file to read in its entirety.
* @return The entire text content of {@code logfile}.
* @throws IOException If an error occurs while reading the file.
* @deprecated call {@link #loadFile(java.io.File, java.nio.charset.Charset)}
* instead to specify the charset to use for decoding (preferably
* {@link java.nio.charset.StandardCharsets#UTF_8}).
*/
@NonNull
@Deprecated
public static String loadFile(@NonNull File logfile) throws IOException {
return loadFile(logfile, Charset.defaultCharset());
}
/**
* Reads the entire contents of the text file at {@code logfile} into a
* string using {@code charset} for decoding. If no such file exists,
* an empty string is returned.
* @param logfile The text file to read in its entirety.
* @param charset The charset to use for decoding the bytes in {@code logfile}.
* @return The entire text content of {@code logfile}.
* @throws IOException If an error occurs while reading the file.
*/
@NonNull
public static String loadFile(@NonNull File logfile, @NonNull Charset charset) throws IOException {
// Note: Until charset handling is resolved (e.g. by implementing
// https://issues.jenkins-ci.org/browse/JENKINS-48923 ), this method
// must be able to handle character encoding errors. As reported at
// https://issues.jenkins-ci.org/browse/JENKINS-49112 Run.getLog() calls
// loadFile() to fully read the generated log file. This file might
// contain unmappable and/or malformed byte sequences. We need to make
// sure that in such cases, no CharacterCodingException is thrown.
//
// One approach that cannot be used is to call Files.newBufferedReader()
// because there is a difference in how an InputStreamReader constructed
// from a Charset and the reader returned by Files.newBufferedReader()
// handle malformed and unmappable byte sequences for the specified
// encoding; the latter is more picky and will throw an exception.
// See: https://issues.jenkins-ci.org/browse/JENKINS-49060?focusedCommentId=325989&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-325989
try {
return FileUtils.readFileToString(logfile, charset);
} catch (FileNotFoundException e) {
return "";
} catch (Exception e) {
throw new IOException("Failed to fully read " + logfile, e);
}
}
/**
* Deletes the contents of the given directory (but not the directory itself)
* recursively.
* It does not take no for an answer - if necessary, it will have multiple
* attempts at deleting things.
*
* @throws IOException
* if the operation fails.
*/
public static void deleteContentsRecursive(@NonNull File file) throws IOException {
deleteContentsRecursive(fileToPath(file), PathRemover.PathChecker.ALLOW_ALL);
}
/**
* Deletes the given directory contents (but not the directory itself) recursively using a PathChecker.
* @param path a directory to delete
* @param pathChecker a security check to validate a path before deleting
* @throws IOException if the operation fails
*/
@Restricted(NoExternalUse.class)
public static void deleteContentsRecursive(@NonNull Path path, @NonNull PathRemover.PathChecker pathChecker) throws IOException {
newPathRemover(pathChecker).forceRemoveDirectoryContents(path);
}
/**
* Deletes this file (and does not take no for an answer).
* If necessary, it will have multiple attempts at deleting things.
*
* @param f a file to delete
* @throws IOException if it exists but could not be successfully deleted
*/
public static void deleteFile(@NonNull File f) throws IOException {
newPathRemover(PathRemover.PathChecker.ALLOW_ALL).forceRemoveFile(fileToPath(f));
}
/**
* Deletes the given directory (including its contents) recursively.
* It does not take no for an answer - if necessary, it will have multiple
* attempts at deleting things.
*
* @throws IOException
* if the operation fails.
*/
public static void deleteRecursive(@NonNull File dir) throws IOException {
deleteRecursive(fileToPath(dir), PathRemover.PathChecker.ALLOW_ALL);
}
/**
* Deletes the given directory and contents recursively using a filter.
* @param dir a directory to delete
* @param pathChecker a security check to validate a path before deleting
* @throws IOException if the operation fails
*/
@Restricted(NoExternalUse.class)
public static void deleteRecursive(@NonNull Path dir, @NonNull PathRemover.PathChecker pathChecker) throws IOException {
newPathRemover(pathChecker).forceRemoveRecursive(dir);
}
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.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.
*/
/**
* Checks if the given file represents a symlink. Unlike {@link Files#isSymbolicLink(Path)}, this method also
* considers <a href="https://en.wikipedia.org/wiki/NTFS_junction_point">NTFS junction points</a> as symbolic
* links.
*/
public static boolean isSymlink(@NonNull File file) throws IOException {
return isSymlink(fileToPath(file));
}
@Restricted(NoExternalUse.class)
public static boolean isSymlink(@NonNull Path path) {
/*
* Windows Directory Junctions are effectively the same as Linux symlinks to directories.
* Unfortunately, the Java 7 NIO2 API function isSymbolicLink does not treat them as such.
* It thinks of them as normal directories. To use the NIO2 API & treat it like a symlink,
* you have to go through BasicFileAttributes and do the following check:
* isSymbolicLink() || isOther()
* The isOther() call will include Windows reparse points, of which a directory junction is.
* It also includes includes devices, but reading the attributes of a device with NIO fails
* or returns false for isOther(). (i.e. named pipes such as \\.\pipe\JenkinsTestPipe return
* false for isOther(), and drives such as \\.\PhysicalDrive0 throw an exception when
* calling readAttributes.
*/
try {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
return attrs.isSymbolicLink() || (attrs instanceof DosFileAttributes && attrs.isOther());
} catch (IOException ignored) {
return false;
}
}
/**
* A mostly accurate check of whether a path is a relative path or not. This is designed to take a path against
* an unknown operating system so may give invalid results.
*
* @param path the path.
* @return {@code true} if the path looks relative.
* @since 1.606
*/
public static boolean isRelativePath(String path) {
if (path.startsWith("/"))
return false;
if (path.startsWith("\\\\") && path.length() > 3 && path.indexOf('\\', 3) != -1)
return false; // a UNC path which is the most absolute you can get on windows
if (path.length() >= 3 && ':' == path.charAt(1)) {
// never mind that the drive mappings can be changed between sessions, we just want to
// know if the 3rd character is a `\` (or a '/' is acceptable too)
char p = path.charAt(0);
if (('A' <= p && p <= 'Z') || ('a' <= p && p <= 'z')) {
return path.charAt(2) != '\\' && path.charAt(2) != '/';
}
}
return true;
}
/**
* A check if a file path is a descendant of a parent path
* @param forParent the parent the child should be a descendant of
* @param potentialChild the path to check
* @return true if so
* @throws IOException for invalid paths
* @since 2.80
* @see InvalidPathException
*/
public static boolean isDescendant(File forParent, File potentialChild) throws IOException {
Path child = fileToPath(potentialChild.getAbsoluteFile()).normalize();
Path parent = fileToPath(forParent.getAbsoluteFile()).normalize();
return child.startsWith(parent);
}
/**
* Creates a new temporary directory.
*/
public static File createTempDir() throws IOException {
// The previously used approach of creating a temporary file, deleting
// it, and making a new directory having the same name in its place is
// potentially problematic:
// https://stackoverflow.com/questions/617414/how-to-create-a-temporary-directory-folder-in-java
// We can use the Java 7 Files.createTempDirectory() API, but note that
// by default, the permissions of the created directory are 0700&(~umask)
// whereas the old approach created a temporary directory with permissions
// 0777&(~umask).
// To avoid permissions problems like https://issues.jenkins-ci.org/browse/JENKINS-48407
// we can pass POSIX file permissions as an attribute (see, for example,
// https://github.com/jenkinsci/jenkins/pull/3161 )
final Path tempPath;
final String tempDirNamePrefix = "jenkins";
if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
tempPath = Files.createTempDirectory(tempDirNamePrefix,
PosixFilePermissions.asFileAttribute(EnumSet.allOf(PosixFilePermission.class)));
} else {
tempPath = Files.createTempDirectory(tempDirNamePrefix);
}
return tempPath.toFile();
}
private static final Pattern errorCodeParser = Pattern.compile(".*CreateProcess.*error=([0-9]+).*");
/**
* On Windows, error messages for IOException aren't very helpful.
* This method generates additional user-friendly error message to the listener
*/
public static void displayIOException(@NonNull IOException e, @NonNull TaskListener listener ) {
String msg = getWin32ErrorMessage(e);
if(msg!=null)
listener.getLogger().println(msg);
}
@CheckForNull
public static String getWin32ErrorMessage(@NonNull IOException e) {
return getWin32ErrorMessage((Throwable)e);
}
/**
* Extracts the Win32 error message from {@link Throwable} if possible.
*
* @return
* null if there seems to be no error code or if the platform is not Win32.
*/
@CheckForNull
public static String getWin32ErrorMessage(Throwable e) {
String msg = e.getMessage();
if(msg!=null) {
Matcher m = errorCodeParser.matcher(msg);
if(m.matches()) {
try {
ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors");
return rb.getString("error"+m.group(1));
} catch (Exception ignored) {
// silently recover from resource related failures
}
}
}
if(e.getCause()!=null)
return getWin32ErrorMessage(e.getCause());
return null; // no message
}
/**
* Gets a human readable message for the given Win32 error code.
*
* @return
* null if no such message is available.
*/
@CheckForNull
public static String getWin32ErrorMessage(int n) {
try {
ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors");
return rb.getString("error"+n);
} catch (MissingResourceException e) {
LOGGER.log(Level.WARNING,"Failed to find resource bundle",e);
return null;
}
}
/**
* Guesses the current host name.
*/
@NonNull
public static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "localhost";
}
}
/**
* @deprecated Use {@link IOUtils#copy(InputStream, OutputStream)}
*/
@Deprecated
public static void copyStream(@NonNull InputStream in,@NonNull OutputStream out) throws IOException {
IOUtils.copy(in, out);
}
/**
* @deprecated Use {@link IOUtils#copy(Reader, Writer)}
*/
@Deprecated
public static void copyStream(@NonNull Reader in, @NonNull Writer out) throws IOException {
IOUtils.copy(in, out);
}
/**
* @deprecated Use {@link IOUtils#copy(InputStream, OutputStream)} in a {@code try}-with-resources block
*/
@Deprecated
public static void copyStreamAndClose(@NonNull InputStream in, @NonNull OutputStream out) throws IOException {
try (InputStream _in = in; OutputStream _out = out) { // make sure both are closed, and use Throwable.addSuppressed
IOUtils.copy(_in, _out);
}
}
/**
* @deprecated Use {@link IOUtils#copy(Reader, Writer)} in a {@code try}-with-resources block
*/
@Deprecated
public static void copyStreamAndClose(@NonNull Reader in, @NonNull Writer out) throws IOException {
try (Reader _in = in; Writer _out = out) {
IOUtils.copy(_in, _out);
}
}
/**
* Tokenizes the text separated by delimiters.
*
* <p>
* In 1.210, this method was changed to handle quotes like Unix shell does.
* Before that, this method just used {@link StringTokenizer}.
*
* @since 1.145
* @see QuotedStringTokenizer
*/
@NonNull
public static String[] tokenize(@NonNull String s, @CheckForNull String delimiter) {
return QuotedStringTokenizer.tokenize(s,delimiter);
}
@NonNull
public static String[] tokenize(@NonNull String s) {
return tokenize(s," \t\n\r\f");
}
/**
* Converts the map format of the environment variables to the K=V format in the array.
*/
@NonNull
public static String[] mapToEnv(@NonNull Map<String,String> m) {
String[] r = new String[m.size()];
int idx=0;
for (final Map.Entry<String,String> e : m.entrySet()) {
r[idx++] = e.getKey() + '=' + e.getValue();
}
return r;
}
public static int min(int x, @NonNull int... values) {
for (int i : values) {
if(i<x)
x=i;
}
return x;
}
@CheckForNull
public static String nullify(@CheckForNull String v) {
return fixEmpty(v);
}
@NonNull
public static String removeTrailingSlash(@NonNull String s) {
if(s.endsWith("/")) return s.substring(0,s.length()-1);
else return s;
}
/**
* Ensure string ends with suffix
*
* @param subject Examined string
* @param suffix Desired suffix
* @return Original subject in case it already ends with suffix, null in
* case subject was null and subject + suffix otherwise.
* @since 1.505
*/
@Nullable
public static String ensureEndsWith(@CheckForNull String subject, @CheckForNull String suffix) {
if (subject == null) return null;
if (subject.endsWith(suffix)) return subject;
return subject + suffix;
}
/**
* Computes MD5 digest of the given input stream.
*
* This method should only be used for non-security applications where the MD5 weakness is not a problem.
*
* @param source
* The stream will be closed by this method at the end of this method.
* @return
* 32-char wide string
* @see DigestUtils#md5Hex(InputStream)
*/
@NonNull
public static String getDigestOf(@NonNull InputStream source) throws IOException {
try {
MessageDigest md5 = getMd5();
DigestInputStream in = new DigestInputStream(source, md5);
// Note: IOUtils.copy() buffers the input internally, so there is no
// need to use a BufferedInputStream.
IOUtils.copy(in, NullOutputStream.NULL_OUTPUT_STREAM);
return toHexString(md5.digest());
} catch (NoSuchAlgorithmException e) {
throw new IOException("MD5 not installed",e); // impossible
} finally {
source.close();
}
/* JENKINS-18178: confuses Maven 2 runner
try {
return DigestUtils.md5Hex(source);
} finally {
source.close();
}
*/
}
// TODO JENKINS-60563 remove MD5 from all usages in Jenkins
@SuppressFBWarnings(value = "WEAK_MESSAGE_DIGEST_MD5", justification =
"This method should only be used for non-security applications where the MD5 weakness is not a problem.")
@Deprecated
private static MessageDigest getMd5() throws NoSuchAlgorithmException {
return MessageDigest.getInstance("MD5");
}
@NonNull
public static String getDigestOf(@NonNull String text) {
try {
return getDigestOf(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)));
} catch (IOException e) {
throw new Error(e);
}
}
/**
* Computes the MD5 digest of a file.
* @param file a file
* @return a 32-character string
* @throws IOException in case reading fails
* @since 1.525
*/
@NonNull
public static String getDigestOf(@NonNull File file) throws IOException {
// Note: getDigestOf() closes the input stream.
return getDigestOf(Files.newInputStream(fileToPath(file)));
}
/**
* Converts a string into 128-bit AES key.
* @since 1.308
*/
@NonNull
public static SecretKey toAes128Key(@NonNull String s) {
try {
// turn secretKey into 256 bit hash
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
digest.update(s.getBytes(StandardCharsets.UTF_8));
// Due to the stupid US export restriction JDK only ships 128bit version.
return new SecretKeySpec(digest.digest(),0,128/8, "AES");
} catch (NoSuchAlgorithmException e) {
throw new Error(e);
}
}
@NonNull
public static String toHexString(@NonNull byte[] data, int start, int len) {
StringBuilder buf = new StringBuilder();
for( int i=0; i<len; i++ ) {
int b = data[start+i]&0xFF;
if(b<16) buf.append('0');
buf.append(Integer.toHexString(b));
}
return buf.toString();
}
@NonNull
public static String toHexString(@NonNull byte[] bytes) {
return toHexString(bytes,0,bytes.length);
}
@NonNull
public static byte[] fromHexString(@NonNull String data) {
if (data.length() % 2 != 0)
throw new IllegalArgumentException("data must have an even number of hexadecimal digits");
byte[] r = new byte[data.length() / 2];
for (int i = 0; i < data.length(); i += 2)
r[i / 2] = (byte) Integer.parseInt(data.substring(i, i + 2), 16);
return r;
}
/**
* Returns a human readable text of the time duration, for example "3 minutes 40 seconds".
* This version should be used for representing a duration of some activity (like build)
*
* @param duration
* number of milliseconds.
*/
@NonNull
@SuppressFBWarnings(value = "ICAST_IDIV_CAST_TO_DOUBLE", justification = "We want to truncate here.")
public static String getTimeSpanString(long duration) {
// Break the duration up in to units.
long years = duration / ONE_YEAR_MS;
duration %= ONE_YEAR_MS;
long months = duration / ONE_MONTH_MS;
duration %= ONE_MONTH_MS;
long days = duration / ONE_DAY_MS;
duration %= ONE_DAY_MS;
long hours = duration / ONE_HOUR_MS;
duration %= ONE_HOUR_MS;
long minutes = duration / ONE_MINUTE_MS;
duration %= ONE_MINUTE_MS;
long seconds = duration / ONE_SECOND_MS;
duration %= ONE_SECOND_MS;
long millisecs = duration;
if (years > 0)
return makeTimeSpanString(years, Messages.Util_year(years), months, Messages.Util_month(months));
else if (months > 0)
return makeTimeSpanString(months, Messages.Util_month(months), days, Messages.Util_day(days));
else if (days > 0)
return makeTimeSpanString(days, Messages.Util_day(days), hours, Messages.Util_hour(hours));
else if (hours > 0)
return makeTimeSpanString(hours, Messages.Util_hour(hours), minutes, Messages.Util_minute(minutes));
else if (minutes > 0)
return makeTimeSpanString(minutes, Messages.Util_minute(minutes), seconds, Messages.Util_second(seconds));
else if (seconds >= 10)
return Messages.Util_second(seconds);
else if (seconds >= 1)
return Messages.Util_second(seconds+(float)(millisecs/100)/10); // render "1.2 sec"
else if(millisecs>=100)
return Messages.Util_second((float)(millisecs/10)/100); // render "0.12 sec".
else
return Messages.Util_millisecond(millisecs);
}
/**
* Create a string representation of a time duration. If the quantity of
* the most significant unit is big (>=10), then we use only that most
* significant unit in the string representation. If the quantity of the
* most significant unit is small (a single-digit value), then we also
* use a secondary, smaller unit for increased precision.
* So 13 minutes and 43 seconds returns just "13 minutes", but 3 minutes
* and 43 seconds is "3 minutes 43 seconds".
*/
@NonNull
private static String makeTimeSpanString(long bigUnit,
@NonNull String bigLabel,
long smallUnit,
@NonNull String smallLabel) {
String text = bigLabel;
if (bigUnit < 10)
text += ' ' + smallLabel;
return text;
}
/**
* Get a human readable string representing strings like "xxx days ago",
* which should be used to point to the occurrence of an event in the past.
* @deprecated Actually identical to {@link #getTimeSpanString}, does not add {@code ago}.
*/
@Deprecated
@NonNull
public static String getPastTimeString(long duration) {
return getTimeSpanString(duration);
}
/**
* Combines number and unit, with a plural suffix if needed.
*
* @deprecated
* Use individual localization methods instead.
* See {@link Messages#Util_year(Object)} for an example.
* Deprecated since 2009-06-24, remove method after 2009-12-24.
*/
@NonNull
@Deprecated
public static String combine(long n, @NonNull String suffix) {
String s = Long.toString(n)+' '+suffix;
if(n!=1)
// Just adding an 's' won't work in most natural languages, even English has exception to the rule (e.g. copy/copies).
s += "s";
return s;
}
/**
* Create a sub-list by only picking up instances of the specified type.
*/
@NonNull
public static <T> List<T> createSubList(@NonNull Collection<?> source, @NonNull Class<T> type ) {
List<T> r = new ArrayList<>();
for (Object item : source) {
if(type.isInstance(item))
r.add(type.cast(item));
}
return r;
}
/**
* Escapes non-ASCII characters in URL.
*
* <p>
* Note that this methods only escapes non-ASCII but leaves other URL-unsafe characters,
* such as '#'.
* {@link #rawEncode(String)} should generally be used instead, though be careful to pass only
* a single path component to that method (it will encode /, but this method does not).
*/
@NonNull
public static String encode(@NonNull String s) {
try {
boolean escaped = false;
StringBuilder out = new StringBuilder(s.length());
ByteArrayOutputStream buf = new ByteArrayOutputStream();
OutputStreamWriter w = new OutputStreamWriter(buf, StandardCharsets.UTF_8);
for (int i = 0; i < s.length(); i++) {
int c = s.charAt(i);
if (c<128 && c!=' ') {
out.append((char) c);
} else {
// 1 char -> UTF8
w.write(c);
w.flush();
for (byte b : buf.toByteArray()) {
out.append('%');
out.append(toDigit((b >> 4) & 0xF));
out.append(toDigit(b & 0xF));
}
buf.reset();
escaped = true;
}
}
return escaped ? out.toString() : s;
} catch (IOException e) {
throw new Error(e); // impossible
}
}
private static final boolean[] uriMap = new boolean[123];
static {
String raw =
"! $ &'()*+,-. 0123456789 = @ABCDEFGHIJKLMNOPQRSTUVWXYZ _ abcdefghijklmnopqrstuvwxyz";
// "# % / :;< >? [\]^ ` {|}~
// ^--so these are encoded
int i;
// Encode control chars and space
for (i = 0; i < 33; i++) uriMap[i] = true;
for (int j = 0; j < raw.length(); i++, j++)
uriMap[i] = (raw.charAt(j) == ' ');
// If we add encodeQuery() just add a 2nd map to encode &+=
// queryMap[38] = queryMap[43] = queryMap[61] = true;
}
/**
* Encode a single path component for use in an HTTP URL.
* Escapes all non-ASCII, general unsafe (space and {@code "#%<>[\]^`{|}~})
* and HTTP special characters ({@code /;:?}) as specified in RFC1738.
* (so alphanumeric and {@code !@$&*()-_=+',.} are not encoded)
* Note that slash ({@code /}) is encoded, so the given string should be a
* single path component used in constructing a URL.
* Method name inspired by PHP's rawurlencode.
*/
@NonNull
public static String rawEncode(@NonNull String s) {
boolean escaped = false;
StringBuilder out = null;
CharsetEncoder enc = null;
CharBuffer buf = null;
char c;
for (int i = 0, m = s.length(); i < m; i++) {
int codePoint = Character.codePointAt(s, i);
if((codePoint&0xffffff80)==0) { // 1 byte
c = s.charAt(i);
if (c > 122 || uriMap[c]) {
if (!escaped) {
out = new StringBuilder(i + (m - i) * 3);
out.append(s, 0, i);
escaped = true;
}
if (enc == null || buf == null) {
enc = StandardCharsets.UTF_8.newEncoder();
buf = CharBuffer.allocate(1);
}
// 1 char -> UTF8
buf.put(0, c);
buf.rewind();
try {
ByteBuffer bytes = enc.encode(buf);
while (bytes.hasRemaining()) {
byte b = bytes.get();
out.append('%');
out.append(toDigit((b >> 4) & 0xF));
out.append(toDigit(b & 0xF));
}
} catch (CharacterCodingException ex) {
}
} else if (escaped) {
out.append(c);
}
} else {
if (!escaped) {
out = new StringBuilder(i + (m - i) * 3);
out.append(s, 0, i);
escaped = true;
}
byte[] bytes = new String(new int[] { codePoint }, 0, 1).getBytes(StandardCharsets.UTF_8);
for (byte aByte : bytes) {
out.append('%');
out.append(toDigit((aByte >> 4) & 0xF));
out.append(toDigit(aByte & 0xF));
}
if(Character.charCount(codePoint) > 1) {
i++; // we processed two characters
}
}
}
return escaped ? out.toString() : s;
}
private static char toDigit(int n) {
return (char)(n < 10 ? '0' + n : 'A' + n - 10);
}
/**
* Surrounds by a single-quote.
*/
public static String singleQuote(String s) {
return '\''+s+'\'';
}
/**
* Escapes HTML unsafe characters like <, & to the respective character entities.
*/
@Nullable
public static String escape(@CheckForNull String text) {
if (text==null) return null;
StringBuilder buf = new StringBuilder(text.length()+64);
for( int i=0; i<text.length(); i++ ) {
char ch = text.charAt(i);
if(ch=='\n')
buf.append("<br>");
else
if(ch=='<')
buf.append("<");
else
if(ch=='>')
buf.append(">");
else
if(ch=='&')
buf.append("&");
else
if(ch=='"')
buf.append(""");
else
if(ch=='\'')
buf.append("'");
else
if(ch==' ') {
// All spaces in a block of consecutive spaces are converted to
// non-breaking space ( ) except for the last one. This allows
// significant whitespace to be retained without prohibiting wrapping.
char nextCh = i+1 < text.length() ? text.charAt(i+1) : 0;
buf.append(nextCh==' ' ? " " : " ");
}
else
buf.append(ch);
}
return buf.toString();
}
@NonNull
public static String xmlEscape(@NonNull String text) {
StringBuilder buf = new StringBuilder(text.length()+64);
for( int i=0; i<text.length(); i++ ) {
char ch = text.charAt(i);
if(ch=='<')
buf.append("<");
else
if(ch=='>')
buf.append(">");
else
if(ch=='&')
buf.append("&");
else