Util.java 64.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * 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.
 */
K
kohsuke 已提交
24 25
package hudson;

26
import java.nio.file.InvalidPathException;
27
import jenkins.util.SystemProperties;
28
import com.sun.jna.Native;
29

30
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
31
import hudson.Proc.LocalProc;
K
kohsuke 已提交
32
import hudson.model.TaskListener;
33
import hudson.os.PosixAPI;
K
kohsuke 已提交
34
import hudson.util.QuotedStringTokenizer;
K
kohsuke 已提交
35
import hudson.util.VariableResolver;
36
import hudson.util.jna.WinIOException;
37

38 39
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.time.FastDateFormat;
K
kohsuke 已提交
40
import org.apache.tools.ant.BuildException;
41
import org.apache.tools.ant.Project;
K
kohsuke 已提交
42 43
import org.apache.tools.ant.taskdefs.Chmod;
import org.apache.tools.ant.taskdefs.Copy;
44
import org.apache.tools.ant.types.FileSet;
45

46 47 48
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

49 50
import jnr.posix.FileStat;
import jnr.posix.POSIX;
K
kohsuke 已提交
51

52 53
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
54

55
import java.io.*;
56 57
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
K
kohsuke 已提交
58
import java.net.InetAddress;
59 60
import java.net.URI;
import java.net.URISyntaxException;
61
import java.net.UnknownHostException;
62
import java.nio.ByteBuffer;
63 64
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
65
import java.nio.charset.Charset;
66
import java.nio.charset.CharsetEncoder;
67 68 69 70 71
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
72 73
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
74 75
import java.text.NumberFormat;
import java.text.ParseException;
76
import java.util.*;
77
import java.util.concurrent.TimeUnit;
78
import java.util.concurrent.atomic.AtomicBoolean;
K
kohsuke 已提交
79
import java.util.logging.Level;
K
kohsuke 已提交
80
import java.util.logging.Logger;
K
kohsuke 已提交
81 82 83
import java.util.regex.Matcher;
import java.util.regex.Pattern;

A
Andrew Stucki 已提交
84
import hudson.util.jna.Kernel32Utils;
85
import static hudson.util.jna.GNUCLibrary.LIBC;
86

87
import java.security.DigestInputStream;
88

O
Oleg Nenashev 已提交
89 90
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
91
import javax.annotation.Nullable;
92

93
import org.apache.commons.codec.digest.DigestUtils;
K
kohsuke 已提交
94

K
kohsuke 已提交
95
/**
K
kohsuke 已提交
96 97
 * Various utility methods that don't have more proper home.
 *
K
kohsuke 已提交
98 99 100
 * @author Kohsuke Kawaguchi
 */
public class Util {
K
kohsuke 已提交
101

102 103 104 105 106 107 108 109
    // 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;

K
kohsuke 已提交
110 111
    /**
     * Creates a filtered sublist.
112
     * @since 1.176
K
kohsuke 已提交
113
     */
O
Oleg Nenashev 已提交
114 115
    @Nonnull
    public static <T> List<T> filter( @Nonnull Iterable<?> base, @Nonnull Class<T> type ) {
K
kohsuke 已提交
116 117 118 119 120 121 122 123
        List<T> r = new ArrayList<T>();
        for (Object i : base) {
            if(type.isInstance(i))
                r.add(type.cast(i));
        }
        return r;
    }

124 125 126
    /**
     * Creates a filtered sublist.
     */
O
Oleg Nenashev 已提交
127 128
    @Nonnull
    public static <T> List<T> filter( @Nonnull List<?> base, @Nonnull Class<T> type ) {
129 130 131
        return filter((Iterable)base,type);
    }

132
    /**
133
     * Pattern for capturing variables. Either $xyz, ${xyz} or ${a.b} but not $a.b, while ignoring "$$"
134
      */
135
    private static final Pattern VARIABLE = Pattern.compile("\\$([A-Za-z0-9_]+|\\{[A-Za-z0-9_.]+\\}|\\$)");
136

K
kohsuke 已提交
137
    /**
K
kohsuke 已提交
138
     * Replaces the occurrence of '$key' by <tt>properties.get('key')</tt>.
K
kohsuke 已提交
139 140
     *
     * <p>
141
     * Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
142
     *
K
kohsuke 已提交
143
     */
144
    @Nullable
O
Oleg Nenashev 已提交
145
    public static String replaceMacro( @CheckForNull String s, @Nonnull Map<String,String> properties) {
K
kohsuke 已提交
146 147
        return replaceMacro(s,new VariableResolver.ByMap<String>(properties));
    }
148

K
kohsuke 已提交
149 150 151 152 153 154
    /**
     * Replaces the occurrence of '$key' by <tt>resolver.get('key')</tt>.
     *
     * <p>
     * Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
     */
155
    @Nullable
O
Oleg Nenashev 已提交
156
    public static String replaceMacro(@CheckForNull String s, @Nonnull VariableResolver<String> resolver) {
157 158 159
    	if (s == null) {
    		return null;
    	}
160

K
kohsuke 已提交
161
        int idx=0;
162 163 164 165 166 167
        while(true) {
            Matcher m = VARIABLE.matcher(s);
            if(!m.find(idx))   return s;

            String key = m.group().substring(1);

168 169 170 171 172 173 174 175 176
            // 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);
            }

177
            if(value==null)
178
                idx = m.end(); // skip this
179 180
            else {
                s = s.substring(0,m.start())+value+s.substring(m.end());
181
                idx = m.start() + value.length();
K
kohsuke 已提交
182 183 184 185
            }
        }
    }

K
kohsuke 已提交
186 187 188
    /**
     * Loads the contents of a file into a string.
     */
O
Oleg Nenashev 已提交
189 190
    @Nonnull
    public static String loadFile(@Nonnull File logfile) throws IOException {
191 192 193
        return loadFile(logfile, Charset.defaultCharset());
    }

O
Oleg Nenashev 已提交
194 195
    @Nonnull
    public static String loadFile(@Nonnull File logfile, @Nonnull Charset charset) throws IOException {
K
kohsuke 已提交
196 197 198
        if(!logfile.exists())
            return "";

199
        StringBuilder str = new StringBuilder((int)logfile.length());
K
kohsuke 已提交
200

201
        try (BufferedReader r = new BufferedReader(new InputStreamReader(Files.newInputStream(logfile.toPath()), charset))) {
202 203
            char[] buf = new char[1024];
            int len;
N
Nicolas De Loof 已提交
204 205
            while ((len = r.read(buf, 0, buf.length)) > 0)
                str.append(buf, 0, len);
206 207
        } catch (InvalidPathException e) {
            throw new IOException(e);
208
        }
K
kohsuke 已提交
209 210 211 212 213 214 215

        return str.toString();
    }

    /**
     * Deletes the contents of the given directory (but not the directory itself)
     * recursively.
216 217
     * It does not take no for an answer - if necessary, it will have multiple
     * attempts at deleting things.
K
kohsuke 已提交
218 219 220 221
     *
     * @throws IOException
     *      if the operation fails.
     */
O
Oleg Nenashev 已提交
222
    public static void deleteContentsRecursive(@Nonnull File file) throws IOException {
223 224 225 226 227 228 229 230 231 232
        for( int numberOfAttempts=1 ; ; numberOfAttempts++ ) {
            try {
                tryOnceDeleteContentsRecursive(file);
                break; // success
            } catch (IOException ex) {
                boolean threadWasInterrupted = pauseBetweenDeletes(numberOfAttempts);
                if( numberOfAttempts>= DELETION_MAX || threadWasInterrupted)
                    throw new IOException(deleteFailExceptionMessage(file, numberOfAttempts, threadWasInterrupted), ex);
            }
        }
K
kohsuke 已提交
233 234
    }

235 236
    /**
     * Deletes this file (and does not take no for an answer).
237 238
     * If necessary, it will have multiple attempts at deleting things.
     *
239 240 241
     * @param f a file to delete
     * @throws IOException if it exists but could not be successfully deleted
     */
O
Oleg Nenashev 已提交
242
    public static void deleteFile(@Nonnull File f) throws IOException {
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
        for( int numberOfAttempts=1 ; ; numberOfAttempts++ ) {
            try {
                tryOnceDeleteFile(f);
                break; // success
            } catch (IOException ex) {
                boolean threadWasInterrupted = pauseBetweenDeletes(numberOfAttempts);
                if( numberOfAttempts>= DELETION_MAX || threadWasInterrupted)
                    throw new IOException(deleteFailExceptionMessage(f, numberOfAttempts, threadWasInterrupted), ex);
            }
        }
    }

    /**
     * Deletes this file, working around most problems which might make
     * this difficult.
     * 
     * @param f
     *            What to delete. If a directory, it'll need to be empty.
     * @throws IOException if it exists but could not be successfully deleted
     */
    private static void tryOnceDeleteFile(File f) throws IOException {
K
kohsuke 已提交
264 265 266 267 268 269
        if (!f.delete()) {
            if(!f.exists())
                // we are trying to delete a file that no longer exists, so this is not an error
                return;

            // perhaps this file is read-only?
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
            makeWritable(f);
            /*
             on Unix both the file and the directory that contains it has to be writable
             for a file deletion to be successful. (Confirmed on Solaris 9)

             $ ls -la
             total 6
             dr-xr-sr-x   2 hudson   hudson       512 Apr 18 14:41 .
             dr-xr-sr-x   3 hudson   hudson       512 Apr 17 19:36 ..
             -r--r--r--   1 hudson   hudson       469 Apr 17 19:36 manager.xml
             -rw-r--r--   1 hudson   hudson         0 Apr 18 14:41 x
             $ rm x
             rm: x not removed: Permission denied
             */

            makeWritable(f.getParentFile());
286

K
kohsuke 已提交
287 288
            if(!f.delete() && f.exists()) {
                // trouble-shooting.
289 290 291 292 293
                try {
                    Files.deleteIfExists(f.toPath());
                } catch (InvalidPathException e) {
                    throw new IOException(e);
                }
294 295

                // see https://java.net/projects/hudson/lists/users/archive/2008-05/message/357
K
kohsuke 已提交
296 297 298 299
                // I suspect other processes putting files in this directory
                File[] files = f.listFiles();
                if(files!=null && files.length>0)
                    throw new IOException("Unable to delete " + f.getPath()+" - files in dir: "+Arrays.asList(files));
300
                throw new IOException("Unable to delete " + f.getPath());
K
kohsuke 已提交
301
            }
K
kohsuke 已提交
302 303 304
        }
    }

305
    /**
306
     * Makes the given file writable by any means possible.
307
     */
O
Oleg Nenashev 已提交
308
    private static void makeWritable(@Nonnull File f) {
309 310
        if (f.setWritable(true)) {
            return;
311
        }
312
        // TODO do we still need to try anything else?
313

314 315 316 317 318 319 320 321 322 323 324
        // try chmod. this becomes no-op if this is not Unix.
        try {
            Chmod chmod = new Chmod();
            chmod.setProject(new Project());
            chmod.setFile(f);
            chmod.setPerm("u+w");
            chmod.execute();
        } catch (BuildException e) {
            LOGGER.log(Level.INFO,"Failed to chmod "+f,e);
        }

325
        try {// try libc chmod
326
            POSIX posix = PosixAPI.jnr();
327 328 329 330 331 332 333
            String path = f.getAbsolutePath();
            FileStat stat = posix.stat(path);
            posix.chmod(path, stat.mode()|0200); // u+w
        } catch (Throwable t) {
            LOGGER.log(Level.FINE,"Failed to chmod(2) "+f,t);
        }

334 335
    }

336 337 338 339 340 341 342 343
    /**
     * 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.
     */
O
Oleg Nenashev 已提交
344
    public static void deleteRecursive(@Nonnull File dir) throws IOException {
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
        for( int numberOfAttempts=1 ; ; numberOfAttempts++ ) {
            try {
                tryOnceDeleteRecursive(dir);
                break; // success
            } catch (IOException ex) {
                boolean threadWasInterrupted = pauseBetweenDeletes(numberOfAttempts);
                if( numberOfAttempts>= DELETION_MAX || threadWasInterrupted)
                    throw new IOException(deleteFailExceptionMessage(dir, numberOfAttempts, threadWasInterrupted), ex);
            }
        }
    }

    /**
     * Deletes a file or folder, throwing the first exception encountered, but
     * having a go at deleting everything. i.e. it does not <em>stop</em> on the
     * first exception, but tries (to delete) everything once.
     *
     * @param dir
     * What to delete. If a directory, the contents will be deleted
     * too.
     * @throws The first exception encountered.
     */
    private static void tryOnceDeleteRecursive(File dir) throws IOException {
368
        if(!isSymlink(dir))
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
            tryOnceDeleteContentsRecursive(dir);
        tryOnceDeleteFile(dir);
    }

    /**
     * Deletes a folder's contents, throwing the first exception encountered,
     * but having a go at deleting everything. i.e. it does not <em>stop</em>
     * on the first exception, but tries (to delete) everything once.
     *
     * @param directory
     * The directory whose contents will be deleted.
     * @throws The first exception encountered.
     */
    private static void tryOnceDeleteContentsRecursive(File directory) throws IOException {
        File[] directoryContents = directory.listFiles();
        if(directoryContents==null)
            return; // the directory didn't exist in the first place
        IOException firstCaught = null;
        for (File child : directoryContents) {
            try {
                tryOnceDeleteRecursive(child);
            } catch (IOException justCaught) {
                if( firstCaught==null) {
                    firstCaught = justCaught;
                }
            }
        }
        if( firstCaught!=null )
            throw firstCaught;
    }

    /**
     * Pauses between delete attempts, and says if it's ok to try again.
     * This does not wait if the wait time is zero or if we have tried
     * too many times already.
     * <p>
     * See {@link #WAIT_BETWEEN_DELETION_RETRIES} for details of
     * the pause duration.<br/>
     * See {@link #GC_AFTER_FAILED_DELETE} for when {@link System#gc()} is called.
     * 
     * @return false if it is ok to continue trying to delete things, true if
     *         we were interrupted (and should stop now).
     */
412 413
    @SuppressFBWarnings(value = "DM_GC", justification = "Garbage collection happens only when "
            + "GC_AFTER_FAILED_DELETE is true. It's an experimental feature in Jenkins.")
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
    private static boolean pauseBetweenDeletes(int numberOfAttemptsSoFar) {
        long delayInMs;
        if( numberOfAttemptsSoFar>=DELETION_MAX ) return false;
        /* If the Jenkins process had the file open earlier, and it has not
         * closed it then Windows won't let us delete it until the Java object
         * with the open stream is Garbage Collected, which can result in builds
         * failing due to "file in use" on Windows despite working perfectly
         * well on other OSs. */
        if (GC_AFTER_FAILED_DELETE) {
            System.gc();
        }
        if (WAIT_BETWEEN_DELETION_RETRIES>=0) {
            delayInMs = WAIT_BETWEEN_DELETION_RETRIES;
        } else {
            delayInMs = -numberOfAttemptsSoFar*WAIT_BETWEEN_DELETION_RETRIES;
        }
        if (delayInMs<=0)
            return Thread.interrupted();
432
        try {
433 434 435 436
            Thread.sleep(delayInMs);
            return false;
        } catch (InterruptedException e) {
            return true;
437
        }
K
kohsuke 已提交
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
    /**
     * Creates a "couldn't delete file" message that explains how hard we tried.
     * See {@link #DELETION_MAX}, {@link #WAIT_BETWEEN_DELETION_RETRIES}
     * and {@link #GC_AFTER_FAILED_DELETE} for more details.
     */
    private static String deleteFailExceptionMessage(File whatWeWereTryingToRemove, int retryCount, boolean wasInterrupted) {
        StringBuilder sb = new StringBuilder();
        sb.append("Unable to delete '");
        sb.append(whatWeWereTryingToRemove);
        sb.append("'. Tried ");
        sb.append(retryCount);
        sb.append(" time");
        if( retryCount!=1 ) sb.append('s');
        if( DELETION_MAX>1 ) {
            sb.append(" (of a maximum of ");
            sb.append(DELETION_MAX);
            sb.append(')');
            if( GC_AFTER_FAILED_DELETE )
                sb.append(" garbage-collecting");
            if( WAIT_BETWEEN_DELETION_RETRIES!=0 && GC_AFTER_FAILED_DELETE )
                sb.append(" and");
            if( WAIT_BETWEEN_DELETION_RETRIES!=0 ) {
                sb.append(" waiting ");
                sb.append(getTimeSpanString(Math.abs(WAIT_BETWEEN_DELETION_RETRIES)));
                if( WAIT_BETWEEN_DELETION_RETRIES<0 ) {
                    sb.append("-");
                    sb.append(getTimeSpanString(Math.abs(WAIT_BETWEEN_DELETION_RETRIES)*DELETION_MAX));
                }
            }
            if( WAIT_BETWEEN_DELETION_RETRIES!=0 || GC_AFTER_FAILED_DELETE)
                sb.append(" between attempts");
471
        }
472 473 474 475
        if( wasInterrupted )
            sb.append(". The delete operation was interrupted before it completed successfully");
        sb.append('.');
        return sb.toString();
K
kohsuke 已提交
476 477
    }

478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
    /*
     * 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.
     */
    //Taken from http://svn.apache.org/viewvc/maven/shared/trunk/file-management/src/main/java/org/apache/maven/shared/model/fileset/util/FileSetManager.java?view=markup
O
Oleg Nenashev 已提交
497
    public static boolean isSymlink(@Nonnull File file) throws IOException {
498 499 500 501 502 503 504 505 506 507 508 509 510
        /*
         *  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.
         *
         *  Since we already have a function that detects Windows junctions or symlinks and treats them
         *  both as symlinks, let's use that function and always call it before calling down to the
         *  NIO2 API.
         *
         */
A
Andrew Stucki 已提交
511
        if (Functions.isWindows()) {
512 513
            try {
                return Kernel32Utils.isJunctionOrSymlink(file);
514
            } catch (UnsupportedOperationException | LinkageError e) {
515 516
                // fall through
            }
A
Andrew Stucki 已提交
517
        }
518 519 520 521
        Boolean r = isSymlinkJava7(file);
        if (r != null) {
            return r;
        }
522 523 524
        String name = file.getName();
        if (name.equals(".") || name.equals(".."))
            return false;
525

526
        File fileInCanonicalParent;
527 528 529 530 531 532 533
        File parentDir = file.getParentFile();
        if ( parentDir == null ) {
            fileInCanonicalParent = file;
        } else {
            fileInCanonicalParent = new File( parentDir.getCanonicalPath(), name );
        }
        return !fileInCanonicalParent.getCanonicalFile().equals( fileInCanonicalParent.getAbsoluteFile() );
534
    }
535

536
    @SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
O
Oleg Nenashev 已提交
537
    private static Boolean isSymlinkJava7(@Nonnull File file) throws IOException {
538
        try {
539 540
            Path path = file.toPath();
            return Files.isSymbolicLink(path);
541 542 543 544 545
        } catch (Exception x) {
            throw (IOException) new IOException(x.toString()).initCause(x);
        }
    }

546 547 548 549 550 551
    /**
     * 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.
552
     * @since 1.606
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
     */
    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;
    }

570 571 572 573 574 575
    /**
     * 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
576
     * @since 2.80
577 578 579 580 581 582 583 584 585 586 587 588
     * @see InvalidPathException
     */
    public static boolean isDescendant(File forParent, File potentialChild) throws IOException {
        try {
            Path child = potentialChild.getAbsoluteFile().toPath().normalize();
            Path parent = forParent.getAbsoluteFile().toPath().normalize();
            return child.startsWith(parent);
        } catch (InvalidPathException e) {
            throw new IOException(e);
        }
    }

K
kohsuke 已提交
589 590 591 592
    /**
     * Creates a new temporary directory.
     */
    public static File createTempDir() throws IOException {
J
James Nord 已提交
593
        File tmp = File.createTempFile("jenkins", "tmp");
K
kohsuke 已提交
594 595 596 597 598 599 600
        if(!tmp.delete())
            throw new IOException("Failed to delete "+tmp);
        if(!tmp.mkdirs())
            throw new IOException("Failed to create a new directory "+tmp);
        return tmp;
    }

601
    private static final Pattern errorCodeParser = Pattern.compile(".*CreateProcess.*error=([0-9]+).*");
K
kohsuke 已提交
602 603 604 605 606

    /**
     * On Windows, error messages for IOException aren't very helpful.
     * This method generates additional user-friendly error message to the listener
     */
O
Oleg Nenashev 已提交
607
    public static void displayIOException(@Nonnull IOException e, @Nonnull TaskListener listener ) {
K
kohsuke 已提交
608 609 610 611 612
        String msg = getWin32ErrorMessage(e);
        if(msg!=null)
            listener.getLogger().println(msg);
    }

O
Oleg Nenashev 已提交
613 614
    @CheckForNull
    public static String getWin32ErrorMessage(@Nonnull IOException e) {
615 616 617
        return getWin32ErrorMessage((Throwable)e);
    }

K
kohsuke 已提交
618
    /**
619
     * Extracts the Win32 error message from {@link Throwable} if possible.
K
kohsuke 已提交
620 621 622 623
     *
     * @return
     *      null if there seems to be no error code or if the platform is not Win32.
     */
O
Oleg Nenashev 已提交
624
    @CheckForNull
625
    public static String getWin32ErrorMessage(Throwable e) {
K
kohsuke 已提交
626
        String msg = e.getMessage();
627 628 629 630 631 632 633 634 635 636
        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 _) {
                    // silently recover from resource related failures
                }
            }
637
        }
K
kohsuke 已提交
638

639 640 641
        if(e.getCause()!=null)
            return getWin32ErrorMessage(e.getCause());
        return null; // no message
K
kohsuke 已提交
642 643
    }

644
    /**
645
     * Gets a human readable message for the given Win32 error code.
646 647 648 649
     *
     * @return
     *      null if no such message is available.
     */
O
Oleg Nenashev 已提交
650
    @CheckForNull
651
    public static String getWin32ErrorMessage(int n) {
652 653 654 655 656 657 658
        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;
        }
659 660
    }

K
kohsuke 已提交
661 662 663
    /**
     * Guesses the current host name.
     */
O
Oleg Nenashev 已提交
664
    @Nonnull
K
kohsuke 已提交
665 666 667 668 669 670 671 672
    public static String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            return "localhost";
        }
    }

673 674 675 676
    /**
     * @deprecated Use {@link IOUtils#copy(InputStream, OutputStream)}
     */
    @Deprecated
O
Oleg Nenashev 已提交
677
    public static void copyStream(@Nonnull InputStream in,@Nonnull OutputStream out) throws IOException {
K
kohsuke 已提交
678 679
        byte[] buf = new byte[8192];
        int len;
K
Kohsuke Kawaguchi 已提交
680
        while((len=in.read(buf))>=0)
K
kohsuke 已提交
681 682 683
            out.write(buf,0,len);
    }

684 685 686 687
    /**
     * @deprecated Use {@link IOUtils#copy(Reader, Writer)}
     */
    @Deprecated
O
Oleg Nenashev 已提交
688
    public static void copyStream(@Nonnull Reader in, @Nonnull Writer out) throws IOException {
K
kohsuke 已提交
689 690
        char[] buf = new char[8192];
        int len;
K
kohsuke 已提交
691 692 693 694
        while((len=in.read(buf))>0)
            out.write(buf,0,len);
    }

695 696 697 698
    /**
     * @deprecated Use {@link IOUtils#copy(InputStream, OutputStream)} in a {@code try}-with-resources block
     */
    @Deprecated
O
Oleg Nenashev 已提交
699
    public static void copyStreamAndClose(@Nonnull InputStream in, @Nonnull OutputStream out) throws IOException {
700
        try (InputStream _in = in; OutputStream _out = out) { // make sure both are closed, and use Throwable.addSuppressed
K
kohsuke 已提交
701 702 703 704
            copyStream(in,out);
        }
    }

705 706 707 708
    /**
     * @deprecated Use {@link IOUtils#copy(Reader, Writer)} in a {@code try}-with-resources block
     */
    @Deprecated
O
Oleg Nenashev 已提交
709
    public static void copyStreamAndClose(@Nonnull Reader in, @Nonnull Writer out) throws IOException {
710
        try (Reader _in = in; Writer _out = out) {
K
kohsuke 已提交
711 712 713 714
            copyStream(in,out);
        }
    }

K
kohsuke 已提交
715
    /**
K
kohsuke 已提交
716 717 718 719 720 721
     * 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}.
     *
K
kohsuke 已提交
722
     * @since 1.145
K
kohsuke 已提交
723
     * @see QuotedStringTokenizer
K
kohsuke 已提交
724
     */
O
Oleg Nenashev 已提交
725 726
    @Nonnull
    public static String[] tokenize(@Nonnull String s, @CheckForNull String delimiter) {
K
kohsuke 已提交
727
        return QuotedStringTokenizer.tokenize(s,delimiter);
K
kohsuke 已提交
728 729
    }

O
Oleg Nenashev 已提交
730 731
    @Nonnull
    public static String[] tokenize(@Nonnull String s) {
K
kohsuke 已提交
732 733 734
        return tokenize(s," \t\n\r\f");
    }

735 736 737
    /**
     * Converts the map format of the environment variables to the K=V format in the array.
     */
O
Oleg Nenashev 已提交
738 739
    @Nonnull
    public static String[] mapToEnv(@Nonnull Map<String,String> m) {
K
kohsuke 已提交
740 741 742
        String[] r = new String[m.size()];
        int idx=0;

J
jglick 已提交
743 744
        for (final Map.Entry<String,String> e : m.entrySet()) {
            r[idx++] = e.getKey() + '=' + e.getValue();
K
kohsuke 已提交
745 746 747 748
        }
        return r;
    }

O
Oleg Nenashev 已提交
749
    public static int min(int x, @Nonnull int... values) {
K
kohsuke 已提交
750 751 752 753 754 755 756
        for (int i : values) {
            if(i<x)
                x=i;
        }
        return x;
    }

O
Oleg Nenashev 已提交
757 758
    @CheckForNull
    public static String nullify(@CheckForNull String v) {
K
Kohsuke Kawaguchi 已提交
759
        return fixEmpty(v);
K
kohsuke 已提交
760 761
    }

O
Oleg Nenashev 已提交
762 763
    @Nonnull
    public static String removeTrailingSlash(@Nonnull String s) {
K
kohsuke 已提交
764 765 766 767
        if(s.endsWith("/")) return s.substring(0,s.length()-1);
        else                return s;
    }

K
Kohsuke Kawaguchi 已提交
768 769 770 771 772 773 774 775 776 777

    /**
     * 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
     */
778
    @Nullable
O
Oleg Nenashev 已提交
779
    public static String ensureEndsWith(@CheckForNull String subject, @CheckForNull String suffix) {
K
Kohsuke Kawaguchi 已提交
780 781 782 783 784 785 786 787

        if (subject == null) return null;

        if (subject.endsWith(suffix)) return subject;

        return subject + suffix;
    }

K
kohsuke 已提交
788 789 790 791 792
    /**
     * Computes MD5 digest of the given input stream.
     *
     * @param source
     *      The stream will be closed by this method at the end of this method.
K
kohsuke 已提交
793 794
     * @return
     *      32-char wide string
J
Jesse Glick 已提交
795
     * @see DigestUtils#md5Hex(InputStream)
K
kohsuke 已提交
796
     */
O
Oleg Nenashev 已提交
797 798
    @Nonnull
    public static String getDigestOf(@Nonnull InputStream source) throws IOException {
799 800 801 802
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");

            byte[] buffer = new byte[1024];
N
Nicolas De Loof 已提交
803 804
            try (DigestInputStream in = new DigestInputStream(source, md5)) {
                while (in.read(buffer) >= 0)
805 806 807 808
                    ; // simply discard the input
            }
            return toHexString(md5.digest());
        } catch (NoSuchAlgorithmException e) {
809
            throw new IOException("MD5 not installed",e);    // impossible
810 811
        }
        /* JENKINS-18178: confuses Maven 2 runner
812 813 814 815 816
        try {
            return DigestUtils.md5Hex(source);
        } finally {
            source.close();
        }
817
        */
K
kohsuke 已提交
818
    }
819

O
Oleg Nenashev 已提交
820 821
    @Nonnull
    public static String getDigestOf(@Nonnull String text) {
822
        try {
K
kohsuke 已提交
823
            return getDigestOf(new ByteArrayInputStream(text.getBytes("UTF-8")));
824 825 826 827
        } catch (IOException e) {
            throw new Error(e);
        }
    }
K
kohsuke 已提交
828

829 830 831 832 833 834 835
    /**
     * 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
     */
O
Oleg Nenashev 已提交
836 837
    @Nonnull
    public static String getDigestOf(@Nonnull File file) throws IOException {
838
        try (InputStream is = Files.newInputStream(file.toPath())) {
839
            return getDigestOf(new BufferedInputStream(is));
840 841
        } catch (InvalidPathException e) {
            throw new IOException(e);
842 843 844
        }
    }

845
    /**
846
     * Converts a string into 128-bit AES key.
847 848
     * @since 1.308
     */
849
    @Nonnull
O
Oleg Nenashev 已提交
850
    public static SecretKey toAes128Key(@Nonnull String s) {
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
        try {
            // turn secretKey into 256 bit hash
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.reset();
            digest.update(s.getBytes("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);
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }
    }

O
Oleg Nenashev 已提交
866 867
    @Nonnull
    public static String toHexString(@Nonnull byte[] data, int start, int len) {
868
        StringBuilder buf = new StringBuilder();
K
kohsuke 已提交
869 870 871 872 873 874 875 876
        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();
    }

O
Oleg Nenashev 已提交
877 878
    @Nonnull
    public static String toHexString(@Nonnull byte[] bytes) {
K
kohsuke 已提交
879 880 881
        return toHexString(bytes,0,bytes.length);
    }

O
Oleg Nenashev 已提交
882 883
    @Nonnull
    public static byte[] fromHexString(@Nonnull String data) {
K
kohsuke 已提交
884 885 886 887 888 889
        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;
    }

K
kohsuke 已提交
890
    /**
K
kohsuke 已提交
891
     * Returns a human readable text of the time duration, for example "3 minutes 40 seconds".
K
i18n  
kohsuke 已提交
892
     * This version should be used for representing a duration of some activity (like build)
K
kohsuke 已提交
893 894 895 896
     *
     * @param duration
     *      number of milliseconds.
     */
O
Oleg Nenashev 已提交
897
    @Nonnull
K
kohsuke 已提交
898
    public static String getTimeSpanString(long duration) {
899 900 901 902 903 904 905 906 907 908 909 910
        // 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;
911 912
        duration %= ONE_SECOND_MS;
        long millisecs = duration;
913 914

        if (years > 0)
C
cactusman 已提交
915
            return makeTimeSpanString(years, Messages.Util_year(years), months, Messages.Util_month(months));
916
        else if (months > 0)
C
cactusman 已提交
917
            return makeTimeSpanString(months, Messages.Util_month(months), days, Messages.Util_day(days));
918
        else if (days > 0)
C
cactusman 已提交
919
            return makeTimeSpanString(days, Messages.Util_day(days), hours, Messages.Util_hour(hours));
920
        else if (hours > 0)
C
cactusman 已提交
921
            return makeTimeSpanString(hours, Messages.Util_hour(hours), minutes, Messages.Util_minute(minutes));
922
        else if (minutes > 0)
C
cactusman 已提交
923
            return makeTimeSpanString(minutes, Messages.Util_minute(minutes), seconds, Messages.Util_second(seconds));
924
        else if (seconds >= 10)
C
cactusman 已提交
925
            return Messages.Util_second(seconds);
926
        else if (seconds >= 1)
927
            return Messages.Util_second(seconds+(float)(millisecs/100)/10); // render "1.2 sec"
928
        else if(millisecs>=100)
929
            return Messages.Util_second((float)(millisecs/10)/100); // render "0.12 sec".
930 931
        else
            return Messages.Util_millisecond(millisecs);
K
kohsuke 已提交
932 933
    }

934 935

    /**
936
     * Create a string representation of a time duration.  If the quantity of
937
     * the most significant unit is big (>=10), then we use only that most
938
     * significant unit in the string representation. If the quantity of the
939 940 941 942 943
     * 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".
     */
O
Oleg Nenashev 已提交
944
    @Nonnull
945
    private static String makeTimeSpanString(long bigUnit,
O
Oleg Nenashev 已提交
946
                                             @Nonnull String bigLabel,
947
                                             long smallUnit,
O
Oleg Nenashev 已提交
948
                                             @Nonnull String smallLabel) {
C
cactusman 已提交
949
        String text = bigLabel;
950
        if (bigUnit < 10)
C
cactusman 已提交
951
            text += ' ' + smallLabel;
952 953 954 955
        return text;
    }


K
i18n  
kohsuke 已提交
956 957
    /**
     * Get a human readable string representing strings like "xxx days ago",
958
     * which should be used to point to the occurrence of an event in the past.
K
i18n  
kohsuke 已提交
959
     */
O
Oleg Nenashev 已提交
960
    @Nonnull
K
i18n  
kohsuke 已提交
961 962 963 964
    public static String getPastTimeString(long duration) {
        return Messages.Util_pastTime(getTimeSpanString(duration));
    }

965

K
kohsuke 已提交
966
    /**
K
kohsuke 已提交
967
     * Combines number and unit, with a plural suffix if needed.
968 969 970
     *
     * @deprecated
     *   Use individual localization methods instead.
971
     *   See {@link Messages#Util_year(Object)} for an example.
972
     *   Deprecated since 2009-06-24, remove method after 2009-12-24.
K
kohsuke 已提交
973
     */
O
Oleg Nenashev 已提交
974
    @Nonnull
975
    @Deprecated
O
Oleg Nenashev 已提交
976
    public static String combine(long n, @Nonnull String suffix) {
K
kohsuke 已提交
977 978
        String s = Long.toString(n)+' '+suffix;
        if(n!=1)
979 980
        	// Just adding an 's' won't work in most natural languages, even English has exception to the rule (e.g. copy/copies).
            s += "s";
K
kohsuke 已提交
981 982 983
        return s;
    }

K
kohsuke 已提交
984 985 986
    /**
     * Create a sub-list by only picking up instances of the specified type.
     */
O
Oleg Nenashev 已提交
987 988
    @Nonnull
    public static <T> List<T> createSubList(@Nonnull Collection<?> source, @Nonnull Class<T> type ) {
K
kohsuke 已提交
989 990 991 992 993 994 995 996
        List<T> r = new ArrayList<T>();
        for (Object item : source) {
            if(type.isInstance(item))
                r.add(type.cast(item));
        }
        return r;
    }

K
kohsuke 已提交
997
    /**
K
kohsuke 已提交
998
     * Escapes non-ASCII characters in URL.
999 1000 1001 1002 1003
     *
     * <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
1004
     * a single path component to that method (it will encode /, but this method does not).
K
kohsuke 已提交
1005
     */
1006
    @Nonnull
O
Oleg Nenashev 已提交
1007
    public static String encode(@Nonnull String s) {
K
kohsuke 已提交
1008 1009 1010
        try {
            boolean escaped = false;

1011
            StringBuilder out = new StringBuilder(s.length());
K
kohsuke 已提交
1012 1013 1014 1015 1016

            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            OutputStreamWriter w = new OutputStreamWriter(buf,"UTF-8");

            for (int i = 0; i < s.length(); i++) {
1017
                int c = s.charAt(i);
L
lvotypko 已提交
1018
                if (c<128 && c!=' ') {
K
kohsuke 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
                    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
        }
    }

1040 1041 1042
    private static final boolean[] uriMap = new boolean[123];
    static {
        String raw =
1043 1044
    "!  $ &'()*+,-. 0123456789   =  @ABCDEFGHIJKLMNOPQRSTUVWXYZ    _ abcdefghijklmnopqrstuvwxyz";
  //  "# %         /          :;< >?                           [\]^ `                          {|}~
1045 1046 1047 1048 1049
  //  ^--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++)
1050
            uriMap[i] = (raw.charAt(j) == ' ');
1051 1052 1053 1054
        // If we add encodeQuery() just add a 2nd map to encode &+=
        // queryMap[38] = queryMap[43] = queryMap[61] = true;
    }

1055 1056
    /**
     * Encode a single path component for use in an HTTP URL.
J
Jesse Glick 已提交
1057 1058 1059 1060
     * 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
1061
     * single path component used in constructing a URL.
1062
     * Method name inspired by PHP's rawurlencode.
1063
     */
O
Oleg Nenashev 已提交
1064 1065
    @Nonnull
    public static String rawEncode(@Nonnull String s) {
1066 1067 1068 1069 1070 1071 1072
        boolean escaped = false;
        StringBuilder out = null;
        CharsetEncoder enc = null;
        CharBuffer buf = null;
        char c;
        for (int i = 0, m = s.length(); i < m; i++) {
            c = s.charAt(i);
1073
            if (c > 122 || uriMap[c]) {
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
                if (!escaped) {
                    out = new StringBuilder(i + (m - i) * 3);
                    out.append(s.substring(0, i));
                    enc = Charset.forName("UTF-8").newEncoder();
                    buf = CharBuffer.allocate(1);
                    escaped = true;
                }
                // 1 char -> UTF8
                buf.put(0,c);
                buf.rewind();
                try {
1085 1086 1087
                    ByteBuffer bytes = enc.encode(buf);
                    while (bytes.hasRemaining()) {
                        byte b = bytes.get();
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
                        out.append('%');
                        out.append(toDigit((b >> 4) & 0xF));
                        out.append(toDigit(b & 0xF));
                    }
                } catch (CharacterCodingException ex) { }
            } else if (escaped) {
                out.append(c);
            }
        }
        return escaped ? out.toString() : s;
    }

    private static char toDigit(int n) {
        return (char)(n < 10 ? '0' + n : 'A' + n - 10);
    }

K
kohsuke 已提交
1104 1105 1106 1107 1108 1109 1110
    /**
     * Surrounds by a single-quote.
     */
    public static String singleQuote(String s) {
        return '\''+s+'\'';
    }

1111
    /**
1112
     * Escapes HTML unsafe characters like &lt;, &amp; to the respective character entities.
1113
     */
1114
    @Nonnull
O
Oleg Nenashev 已提交
1115
    public static String escape(@Nonnull String text) {
K
kohsuke 已提交
1116
        if (text==null)     return null;
1117
        StringBuilder buf = new StringBuilder(text.length()+64);
1118 1119 1120 1121 1122 1123 1124 1125
        for( int i=0; i<text.length(); i++ ) {
            char ch = text.charAt(i);
            if(ch=='\n')
                buf.append("<br>");
            else
            if(ch=='<')
                buf.append("&lt;");
            else
1126 1127 1128
            if(ch=='>')
                buf.append("&gt;");
            else
1129 1130 1131
            if(ch=='&')
                buf.append("&amp;");
            else
S
Seiji Sogabe 已提交
1132 1133 1134 1135 1136 1137
            if(ch=='"')
                buf.append("&quot;");
            else
            if(ch=='\'')
                buf.append("&#039;");
            else
1138 1139 1140 1141 1142 1143 1144 1145
            if(ch==' ') {
                // All spaces in a block of consecutive spaces are converted to
                // non-breaking space (&nbsp;) 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==' ' ? "&nbsp;" : " ");
            }
            else
1146 1147 1148 1149 1150
                buf.append(ch);
        }
        return buf.toString();
    }

O
Oleg Nenashev 已提交
1151 1152
    @Nonnull
    public static String xmlEscape(@Nonnull String text) {
1153
        StringBuilder buf = new StringBuilder(text.length()+64);
K
kohsuke 已提交
1154 1155 1156 1157 1158
        for( int i=0; i<text.length(); i++ ) {
            char ch = text.charAt(i);
            if(ch=='<')
                buf.append("&lt;");
            else
1159 1160 1161
            if(ch=='>')
                buf.append("&gt;");
            else
K
kohsuke 已提交
1162 1163 1164 1165 1166 1167 1168 1169
            if(ch=='&')
                buf.append("&amp;");
            else
                buf.append(ch);
        }
        return buf.toString();
    }

K
kohsuke 已提交
1170 1171 1172
    /**
     * Creates an empty file.
     */
O
Oleg Nenashev 已提交
1173
    public static void touch(@Nonnull File file) throws IOException {
1174 1175 1176 1177 1178
        try {
            Files.newOutputStream(file.toPath()).close();
        } catch (InvalidPathException e) {
            throw new IOException(e);
        }
K
kohsuke 已提交
1179 1180 1181 1182 1183
    }

    /**
     * Copies a single file by using Ant.
     */
O
Oleg Nenashev 已提交
1184
    public static void copyFile(@Nonnull File src, @Nonnull File dst) throws BuildException {
K
kohsuke 已提交
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
        Copy cp = new Copy();
        cp.setProject(new org.apache.tools.ant.Project());
        cp.setTofile(dst);
        cp.setFile(src);
        cp.setOverwrite(true);
        cp.execute();
    }

    /**
     * Convert null to "".
     */
O
Oleg Nenashev 已提交
1196 1197
    @Nonnull
    public static String fixNull(@CheckForNull String s) {
K
kohsuke 已提交
1198 1199 1200 1201 1202 1203 1204
        if(s==null)     return "";
        else            return s;
    }

    /**
     * Convert empty string to null.
     */
O
Oleg Nenashev 已提交
1205 1206
    @CheckForNull
    public static String fixEmpty(@CheckForNull String s) {
K
kohsuke 已提交
1207 1208 1209 1210
        if(s==null || s.length()==0)    return null;
        return s;
    }

K
kohsuke 已提交
1211 1212 1213 1214 1215
    /**
     * Convert empty string to null, and trim whitespace.
     *
     * @since 1.154
     */
O
Oleg Nenashev 已提交
1216 1217
    @CheckForNull
    public static String fixEmptyAndTrim(@CheckForNull String s) {
K
kohsuke 已提交
1218
        if(s==null)    return null;
K
kohsuke 已提交
1219
        return fixEmpty(s.trim());
K
kohsuke 已提交
1220 1221
    }

O
Oleg Nenashev 已提交
1222 1223
    @Nonnull
    public static <T> List<T> fixNull(@CheckForNull List<T> l) {
1224 1225 1226
        return l!=null ? l : Collections.<T>emptyList();
    }

O
Oleg Nenashev 已提交
1227 1228
    @Nonnull
    public static <T> Set<T> fixNull(@CheckForNull Set<T> l) {
1229 1230 1231
        return l!=null ? l : Collections.<T>emptySet();
    }

O
Oleg Nenashev 已提交
1232 1233
    @Nonnull
    public static <T> Collection<T> fixNull(@CheckForNull Collection<T> l) {
1234 1235 1236
        return l!=null ? l : Collections.<T>emptySet();
    }

O
Oleg Nenashev 已提交
1237 1238
    @Nonnull
    public static <T> Iterable<T> fixNull(@CheckForNull Iterable<T> l) {
K
kohsuke 已提交
1239 1240 1241
        return l!=null ? l : Collections.<T>emptySet();
    }

K
kohsuke 已提交
1242 1243 1244
    /**
     * Cuts all the leading path portion and get just the file name.
     */
O
Oleg Nenashev 已提交
1245 1246
    @Nonnull
    public static String getFileName(@Nonnull String filePath) {
K
kohsuke 已提交
1247 1248 1249 1250 1251 1252 1253 1254 1255
        int idx = filePath.lastIndexOf('\\');
        if(idx>=0)
            return getFileName(filePath.substring(idx+1));
        idx = filePath.lastIndexOf('/');
        if(idx>=0)
            return getFileName(filePath.substring(idx+1));
        return filePath;
    }

K
kohsuke 已提交
1256 1257 1258
    /**
     * Concatenate multiple strings by inserting a separator.
     */
O
Oleg Nenashev 已提交
1259 1260
    @Nonnull
    public static String join(@Nonnull Collection<?> strings, @Nonnull String separator) {
K
kohsuke 已提交
1261 1262
        StringBuilder buf = new StringBuilder();
        boolean first=true;
1263
        for (Object s : strings) {
K
kohsuke 已提交
1264
            if(first)   first=false;
1265
            else        buf.append(separator);
K
kohsuke 已提交
1266 1267 1268 1269 1270
            buf.append(s);
        }
        return buf.toString();
    }

K
kohsuke 已提交
1271 1272 1273
    /**
     * Combines all the given collections into a single list.
     */
O
Oleg Nenashev 已提交
1274 1275
    @Nonnull
    public static <T> List<T> join(@Nonnull Collection<? extends T>... items) {
K
kohsuke 已提交
1276 1277 1278 1279 1280 1281 1282 1283 1284
        int size = 0;
        for (Collection<? extends T> item : items)
            size += item.size();
        List<T> r = new ArrayList<T>(size);
        for (Collection<? extends T> item : items)
            r.addAll(item);
        return r;
    }

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
    /**
     * Creates Ant {@link FileSet} with the base dir and include pattern.
     *
     * <p>
     * The difference with this and using {@link FileSet#setIncludes(String)}
     * is that this method doesn't treat whitespace as a pattern separator,
     * which makes it impossible to use space in the file path.
     *
     * @param includes
     *      String like "foo/bar/*.xml" Multiple patterns can be separated
     *      by ',', and whitespace can surround ',' (so that you can write
     *      "abc, def" and "abc,def" to mean the same thing.
K
kohsuke 已提交
1297
     * @param excludes
K
kohsuke 已提交
1298 1299
     *      Exclusion pattern. Follows the same format as the 'includes' parameter.
     *      Can be null.
K
kohsuke 已提交
1300
     * @since 1.172
1301
     */
O
Oleg Nenashev 已提交
1302 1303
    @Nonnull
    public static FileSet createFileSet(@Nonnull File baseDir, @Nonnull String includes, @CheckForNull String excludes) {
1304 1305 1306
        FileSet fs = new FileSet();
        fs.setDir(baseDir);
        fs.setProject(new Project());
K
kohsuke 已提交
1307 1308 1309 1310

        StringTokenizer tokens;

        tokens = new StringTokenizer(includes,",");
1311 1312 1313 1314
        while(tokens.hasMoreTokens()) {
            String token = tokens.nextToken().trim();
            fs.createInclude().setName(token);
        }
K
kohsuke 已提交
1315 1316 1317 1318 1319 1320 1321
        if(excludes!=null) {
            tokens = new StringTokenizer(excludes,",");
            while(tokens.hasMoreTokens()) {
                String token = tokens.nextToken().trim();
                fs.createExclude().setName(token);
            }
        }
1322 1323
        return fs;
    }
K
kohsuke 已提交
1324

O
Oleg Nenashev 已提交
1325 1326
    @Nonnull
    public static FileSet createFileSet(@Nonnull File baseDir, @Nonnull String includes) {
K
kohsuke 已提交
1327 1328 1329
        return createFileSet(baseDir,includes,null);
    }

1330
    /**
1331
     * Creates a symlink to targetPath at baseDir+symlinkPath.
1332 1333
     * <p>
     * If there's a prior symlink at baseDir+symlinkPath, it will be overwritten.
1334 1335 1336 1337
     *
     * @param baseDir
     *      Base directory to resolve the 'symlinkPath' parameter.
     * @param targetPath
1338
     *      The file that the symlink should point to. Usually relative to the directory of the symlink but may instead be an absolute path.
1339
     * @param symlinkPath
1340
     *      Where to create a symlink in (relative to {@code baseDir})
1341
     */
1342
    public static void createSymlink(@Nonnull File baseDir, @Nonnull String targetPath,
O
Oleg Nenashev 已提交
1343
            @Nonnull String symlinkPath, @Nonnull TaskListener listener) throws InterruptedException {
K
kohsuke 已提交
1344
        try {
1345 1346
            if (createSymlinkJava7(baseDir, targetPath, symlinkPath)) {
                return;
1347
            }
1348
            if (NO_SYMLINK) {
1349 1350
                return;
            }
K
kohsuke 已提交
1351

1352 1353 1354 1355 1356 1357
            File symlinkFile = new File(baseDir, symlinkPath);
            if (Functions.isWindows()) {
                if (symlinkFile.exists()) {
                    symlinkFile.delete();
                }
                File dst = new File(symlinkFile,"..\\"+targetPath);
K
kohsuke 已提交
1358
                try {
1359 1360 1361 1362 1363
                    Kernel32Utils.createSymbolicLink(symlinkFile,targetPath,dst.isDirectory());
                } catch (WinIOException e) {
                    if (e.getErrorCode()==1314) {/* ERROR_PRIVILEGE_NOT_HELD */
                        warnWindowsSymlink();
                        return;
1364
                    }
1365
                    throw e;
K
Kohsuke Kawaguchi 已提交
1366 1367 1368
                } catch (UnsatisfiedLinkError e) {
                    // not available on this Windows
                    return;
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
                }
            } else {
                String errmsg = "";
                // if a file or a directory exists here, delete it first.
                // try simple delete first (whether exists() or not, as it may be symlink pointing
                // to non-existent target), but fallback to "rm -rf" to delete non-empty dir.
                if (!symlinkFile.delete() && symlinkFile.exists())
                    // ignore a failure.
                    new LocalProc(new String[]{"rm","-rf", symlinkPath},new String[0],listener.getLogger(), baseDir).join();

                Integer r=null;
                if (!SYMLINK_ESCAPEHATCH) {
                    try {
                        r = LIBC.symlink(targetPath,symlinkFile.getAbsolutePath());
                        if (r!=0) {
                            r = Native.getLastError();
                            errmsg = LIBC.strerror(r);
                        }
                    } catch (LinkageError e) {
                        // if JNA is unavailable, fall back.
                        // we still prefer to try JNA first as PosixAPI supports even smaller platforms.
1390 1391
                        POSIX posix = PosixAPI.jnr();
                        if (posix.isNative()) {
1392
                            // TODO should we rethrow PosixException as IOException here?
1393
                            r = posix.symlink(targetPath,symlinkFile.getAbsolutePath());
1394
                        }
1395
                    }
K
kohsuke 已提交
1396
                }
1397 1398
                if (r==null) {
                    // if all else fail, fall back to the most expensive approach of forking a process
1399
                    // TODO is this really necessary? JavaPOSIX should do this automatically
1400 1401 1402 1403 1404 1405
                    r = new LocalProc(new String[]{
                        "ln","-s", targetPath, symlinkPath},
                        new String[0],listener.getLogger(), baseDir).join();
                }
                if (r!=0)
                    listener.getLogger().println(String.format("ln -s %s %s failed: %d %s",targetPath, symlinkFile, r, errmsg));
1406
            }
K
kohsuke 已提交
1407 1408
        } catch (IOException e) {
            PrintStream log = listener.getLogger();
1409
            log.printf("ln %s %s failed%n",targetPath, new File(baseDir, symlinkPath));
K
kohsuke 已提交
1410
            Util.displayIOException(e,listener);
1411
            Functions.printStackTrace(e, log);
K
kohsuke 已提交
1412 1413 1414
        }
    }

O
Oleg Nenashev 已提交
1415
    private static boolean createSymlinkJava7(@Nonnull File baseDir, @Nonnull String targetPath, @Nonnull String symlinkPath) throws IOException {
1416
        try {
1417 1418
            Path path = new File(baseDir, symlinkPath).toPath();
            Path target = Paths.get(targetPath, new String[0]);
1419 1420 1421 1422

            final int maxNumberOfTries = 4;
            final int timeInMillis = 100;
            for (int tryNumber = 1; tryNumber <= maxNumberOfTries; tryNumber++) {
1423
                Files.deleteIfExists(path);
1424
                try {
1425
                    Files.createSymbolicLink(path, target);
1426
                    break;
1427 1428 1429 1430
                } catch (FileAlreadyExistsException fileAlreadyExistsException) {
                    if (tryNumber < maxNumberOfTries) {
                        TimeUnit.MILLISECONDS.sleep(timeInMillis); //trying to defeat likely ongoing race condition
                        continue;
1431
                    }
1432 1433
                    LOGGER.warning("symlink FileAlreadyExistsException thrown " + maxNumberOfTries + " times => cannot createSymbolicLink");
                    throw fileAlreadyExistsException;
1434 1435
                }
            }
1436
            return true;
1437
        } catch (UnsupportedOperationException e) {
1438
                return true; // no symlinks on this platform
1439 1440
        } catch (FileSystemException e) {
            if (Functions.isWindows()) {
1441
                warnWindowsSymlink();
1442 1443
                return true;
            }
1444 1445 1446
            return false;
        } catch (IOException x) {
            throw x;
1447 1448 1449 1450 1451
        } catch (Exception x) {
            throw (IOException) new IOException(x.toString()).initCause(x);
        }
    }

1452 1453 1454 1455 1456 1457 1458
    private static final AtomicBoolean warnedSymlinks = new AtomicBoolean();
    private static void warnWindowsSymlink() {
        if (warnedSymlinks.compareAndSet(false, true)) {
            LOGGER.warning("Symbolic links enabled on this platform but disabled for this user; run as administrator or use Local Security Policy > Security Settings > Local Policies > User Rights Assignment > Create symbolic links");
        }
    }

K
Kohsuke Kawaguchi 已提交
1459 1460 1461 1462
    /**
     * @deprecated as of 1.456
     *      Use {@link #resolveSymlink(File)}
     */
1463
    @Deprecated
K
Kohsuke Kawaguchi 已提交
1464 1465 1466 1467
    public static String resolveSymlink(File link, TaskListener listener) throws InterruptedException, IOException {
        return resolveSymlink(link);
    }

K
Kohsuke Kawaguchi 已提交
1468 1469 1470 1471 1472 1473
    /**
     * Resolves a symlink to the {@link File} that points to.
     *
     * @return null
     *      if the specified file is not a symlink.
     */
O
Oleg Nenashev 已提交
1474 1475
    @CheckForNull
    public static File resolveSymlinkToFile(@Nonnull File link) throws InterruptedException, IOException {
K
Kohsuke Kawaguchi 已提交
1476 1477 1478 1479 1480 1481 1482
        String target = resolveSymlink(link);
        if (target==null)   return null;

        File f = new File(target);
        if (f.isAbsolute()) return f;   // absolute symlink
        return new File(link.getParentFile(),target);   // relative symlink
    }
K
Kohsuke Kawaguchi 已提交
1483

K
kohsuke 已提交
1484 1485 1486 1487
    /**
     * Resolves symlink, if the given file is a symlink. Otherwise return null.
     * <p>
     * If the resolution fails, report an error.
K
Kohsuke Kawaguchi 已提交
1488 1489 1490 1491 1492 1493
     *
     * @return
     *      null if the given file is not a symlink.
     *      If the symlink is absolute, the returned string is an absolute path.
     *      If the symlink is relative, the returned string is that relative representation.
     *      The relative path is meant to be resolved from the location of the symlink.
K
kohsuke 已提交
1494
     */
O
Oleg Nenashev 已提交
1495 1496
    @CheckForNull
    public static String resolveSymlink(@Nonnull File link) throws InterruptedException, IOException {
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
        try {
            Path path =  link.toPath();
            return Files.readSymbolicLink(path).toString();
        } catch (UnsupportedOperationException | FileSystemException x) {
            // no symlinks on this platform (windows?),
            // or not a link (// Thrown ("Incorrect function.") on JDK 7u21 in Windows 2012 when called on a non-symlink,
            // rather than NotLinkException, contrary to documentation. Maybe only when not on NTFS?) ?
            return null;
        } catch (IOException x) {
            throw x;
1507 1508 1509
        } catch (Exception x) {
            throw (IOException) new IOException(x.toString()).initCause(x);
        }
1510 1511
    }

1512 1513 1514 1515 1516 1517 1518
    /**
     * Encodes the URL by RFC 2396.
     *
     * I thought there's another spec that refers to UTF-8 as the encoding,
     * but don't remember it right now.
     *
     * @since 1.204
M
mindless 已提交
1519
     * @deprecated since 2008-05-13. This method is broken (see ISSUE#1666). It should probably
1520 1521
     * be removed but I'm not sure if it is considered part of the public API
     * that needs to be maintained for backwards compatibility.
1522
     * Use {@link #encode(String)} instead.
1523
     */
1524
    @Deprecated
1525 1526 1527 1528 1529 1530 1531 1532 1533
    public static String encodeRFC2396(String url) {
        try {
            return new URI(null,url,null).toASCIIString();
        } catch (URISyntaxException e) {
            LOGGER.warning("Failed to encode "+url);    // could this ever happen?
            return url;
        }
    }

K
kohsuke 已提交
1534 1535
    /**
     * Wraps with the error icon and the CSS class to render error message.
1536
     * @since 1.173
K
kohsuke 已提交
1537
     */
O
Oleg Nenashev 已提交
1538 1539
    @Nonnull
    public static String wrapToErrorSpan(@Nonnull String s) {
1540
        s = "<span class=error style='display:inline-block'>"+s+"</span>";
K
kohsuke 已提交
1541 1542
        return s;
    }
1543

1544 1545 1546 1547 1548 1549 1550 1551
    /**
     * Returns the parsed string if parsed successful; otherwise returns the default number.
     * If the string is null, empty or a ParseException is thrown then the defaultNumber
     * is returned.
     * @param numberStr string to parse
     * @param defaultNumber number to return if the string can not be parsed
     * @return returns the parsed string; otherwise the default number
     */
O
Oleg Nenashev 已提交
1552 1553
    @CheckForNull
    public static Number tryParseNumber(@CheckForNull String numberStr, @CheckForNull Number defaultNumber) {
1554 1555 1556 1557 1558 1559 1560 1561 1562
        if ((numberStr == null) || (numberStr.length() == 0)) {
            return defaultNumber;
        }
        try {
            return NumberFormat.getNumberInstance().parse(numberStr);
        } catch (ParseException e) {
            return defaultNumber;
        }
    }
K
kohsuke 已提交
1563

1564
    /**
1565 1566
     * Checks if the method defined on the base type with the given arguments
     * is overridden in the given derived type.
1567
     */
O
Oleg Nenashev 已提交
1568
    public static boolean isOverridden(@Nonnull Class base, @Nonnull Class derived, @Nonnull String methodName, @Nonnull Class... types) {
1569 1570 1571 1572 1573
        return !getMethod(base, methodName, types).equals(getMethod(derived, methodName, types));
    }

    private static Method getMethod(@Nonnull Class clazz, @Nonnull String methodName, @Nonnull Class... types) {
        Method res = null;
1574
        try {
1575 1576 1577 1578 1579 1580
            res = clazz.getDeclaredMethod(methodName, types);
            // private, static or final methods can not be overridden
            if (res != null && (Modifier.isPrivate(res.getModifiers()) || Modifier.isFinal(res.getModifiers()) 
                    || Modifier.isStatic(res.getModifiers()))) {
                res = null;
            }
1581
        } catch (NoSuchMethodException e) {
1582 1583 1584 1585 1586 1587
            // Method not found in clazz, let's search in superclasses
            Class superclass = clazz.getSuperclass();
            if (superclass != null) {
                res = getMethod(superclass, methodName, types);
            }
        } catch (SecurityException e) {
1588 1589
            throw new AssertionError(e);
        }
1590 1591 1592 1593 1594
        if (res == null) {
            throw new IllegalArgumentException(
                    String.format("Method %s not found in %s (or it is private, final or static)", methodName, clazz.getName()));
        }
        return res;
1595 1596
    }

1597 1598 1599 1600 1601 1602
    /**
     * Returns a file name by changing its extension.
     *
     * @param ext
     *      For example, ".zip"
     */
O
Oleg Nenashev 已提交
1603 1604
    @Nonnull
    public static File changeExtension(@Nonnull File dst, @Nonnull String ext) {
1605 1606 1607 1608 1609 1610
        String p = dst.getPath();
        int pos = p.lastIndexOf('.');
        if (pos<0)  return new File(p+ext);
        else        return new File(p.substring(0,pos)+ext);
    }

K
kohsuke 已提交
1611 1612
    /**
     * Null-safe String intern method.
1613
     * @return A canonical representation for the string object. Null for null input strings
K
kohsuke 已提交
1614
     */
1615
    @Nullable
O
Oleg Nenashev 已提交
1616
    public static String intern(@CheckForNull String s) {
K
kohsuke 已提交
1617 1618 1619
        return s==null ? s : s.intern();
    }

K
Kohsuke Kawaguchi 已提交
1620 1621 1622 1623 1624 1625
    /**
     * Return true if the systemId denotes an absolute URI .
     *
     * The same algorithm can be seen in {@link URI}, but
     * implementing this by ourselves allow it to be more lenient about
     * escaping of URI.
1626 1627
     *
     * @deprecated Use {@code isAbsoluteOrSchemeRelativeUri} instead if your goal is to prevent open redirects
K
Kohsuke Kawaguchi 已提交
1628
     */
1629 1630 1631
    @Deprecated
    @RestrictedSince("1.651.2 / 2.TODO")
    @Restricted(NoExternalUse.class)
O
Oleg Nenashev 已提交
1632
    public static boolean isAbsoluteUri(@Nonnull String uri) {
K
Kohsuke Kawaguchi 已提交
1633 1634 1635 1636 1637 1638 1639
        int idx = uri.indexOf(':');
        if (idx<0)  return false;   // no ':'. can't be absolute

        // #, ?, and / must not be before ':'
        return idx<_indexOf(uri, '#') && idx<_indexOf(uri,'?') && idx<_indexOf(uri,'/');
    }

1640
    /**
1641
     * Return true iff the parameter does not denote an absolute URI and not a scheme-relative URI.
1642
     * @since 2.3 / 1.651.2
1643
     */
1644 1645
    public static boolean isSafeToRedirectTo(@Nonnull String uri) {
        return !isAbsoluteUri(uri) && !uri.startsWith("//");
1646 1647
    }

K
Kohsuke Kawaguchi 已提交
1648 1649 1650 1651
    /**
     * Works like {@link String#indexOf(int)} but 'not found' is returned as s.length(), not -1.
     * This enables more straight-forward comparison.
     */
O
Oleg Nenashev 已提交
1652
    private static int _indexOf(@Nonnull String s, char ch) {
K
Kohsuke Kawaguchi 已提交
1653 1654 1655 1656 1657
        int idx = s.indexOf(ch);
        if (idx<0)  return s.length();
        return idx;
    }

1658 1659 1660 1661
    /**
     * Loads a key/value pair string as {@link Properties}
     * @since 1.392
     */
O
Oleg Nenashev 已提交
1662 1663
    @Nonnull
    public static Properties loadProperties(@Nonnull String properties) throws IOException {
1664
        Properties p = new Properties();
1665
        p.load(new StringReader(properties));
1666 1667
        return p;
    }
1668 1669 1670 1671 1672 1673 1674 1675
    
    /**
     * Closes the item and logs error to the log in the case of error.
     * Logging will be performed on the {@code WARNING} level.
     * @param toClose Item to close. Nothing will happen if it is {@code null}
     * @param logger Logger, which receives the error
     * @param closeableName Name of the closeable item
     * @param closeableOwner String representation of the closeable holder
D
Daniel Beck 已提交
1676
     * @since 2.19, but TODO update once un-restricted
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
     */
    @Restricted(NoExternalUse.class)
    public static void closeAndLogFailures(@CheckForNull Closeable toClose, @Nonnull Logger logger, 
            @Nonnull String closeableName, @Nonnull String closeableOwner) {
        if (toClose == null) {
            return;
        }
        try {
            toClose.close();
        } catch(IOException ex) {
            logger.log(Level.WARNING, String.format("Failed to close %s of %s", closeableName, closeableOwner), ex);
        }
    }
1690

1691
    public static final FastDateFormat XS_DATETIME_FORMATTER = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss'Z'",new SimpleTimeZone(0,"GMT"));
K
kohsuke 已提交
1692

1693
    // Note: RFC822 dates must not be localized!
1694 1695
    public static final FastDateFormat RFC822_DATETIME_FORMATTER
            = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
K
kohsuke 已提交
1696 1697

    private static final Logger LOGGER = Logger.getLogger(Util.class.getName());
1698 1699 1700 1701

    /**
     * On Unix environment that cannot run "ln", set this to true.
     */
1702
    public static boolean NO_SYMLINK = SystemProperties.getBoolean(Util.class.getName()+".noSymLink");
1703

1704
    public static boolean SYMLINK_ESCAPEHATCH = SystemProperties.getBoolean(Util.class.getName()+".symlinkEscapeHatch");
1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720

    /**
     * The number of times we will attempt to delete files/directory trees
     * before giving up and throwing an exception.<br/>
     * Specifying a value less than 1 is invalid and will be treated as if
     * a value of 1 (i.e. one attempt, no retries) was specified.
     * <p>
     * e.g. if some of the child directories are big, it might take long enough
     * to delete that it allows others to create new files in the directory we
     * are trying to empty, causing problems like JENKINS-10113.
     * Or, if we're on Windows, then deletes can fail for transient reasons
     * regardless of external activity; see JENKINS-15331.
     * Whatever the reason, this allows us to do multiple attempts before we
     * give up, thus improving build reliability.
     */
    @Restricted(value = NoExternalUse.class)
1721
    static int DELETION_MAX = Math.max(1, SystemProperties.getInteger(Util.class.getName() + ".maxFileDeletionRetries", 3).intValue());
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732

    /**
     * The time (in milliseconds) that we will wait between attempts to
     * delete files when retrying.<br>
     * This has no effect unless {@link #DELETION_MAX} is non-zero.
     * <p>
     * If zero, we will not delay between attempts.<br>
     * If negative, we will wait an (linearly) increasing multiple of this value
     * between attempts.
     */
    @Restricted(value = NoExternalUse.class)
1733
    static int WAIT_BETWEEN_DELETION_RETRIES = SystemProperties.getInteger(Util.class.getName() + ".deletionRetryWait", 100).intValue();
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756

    /**
     * If this flag is set to true then we will request a garbage collection
     * after a deletion failure before we next retry the delete.<br>
     * It defaults to <code>false</code> and is ignored unless
     * {@link #DELETION_MAX} is greater than 1.
     * <p>
     * Setting this flag to true <i>may</i> resolve some problems on Windows,
     * and also for directory trees residing on an NFS share, <b>but</b> it can
     * have a negative impact on performance and may have no effect at all (GC
     * behavior is JVM-specific).
     * <p>
     * Warning: This should only ever be used if you find that your builds are
     * failing because Jenkins is unable to delete files, that this failure is
     * because Jenkins itself has those files locked "open", and even then it
     * should only be used on slaves with relatively few executors (because the
     * garbage collection can impact the performance of all job executors on
     * that slave).<br/>
     * i.e. Setting this flag is a act of last resort - it is <em>not</em>
     * recommended, and should not be used on the main Jenkins server
     * unless you can tolerate the performance impact.
     */
    @Restricted(value = NoExternalUse.class)
1757
    static boolean GC_AFTER_FAILED_DELETE = SystemProperties.getBoolean(Util.class.getName() + ".performGCOnFailedDelete");
K
kohsuke 已提交
1758
}