Util.java 41.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 27 28 29
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import hudson.Proc.LocalProc;
K
kohsuke 已提交
30
import hudson.model.TaskListener;
31
import hudson.os.PosixAPI;
K
kohsuke 已提交
32
import hudson.util.IOException2;
K
kohsuke 已提交
33
import hudson.util.QuotedStringTokenizer;
K
kohsuke 已提交
34
import hudson.util.VariableResolver;
35 36 37
import jenkins.model.Jenkins;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.time.FastDateFormat;
K
kohsuke 已提交
38
import org.apache.tools.ant.BuildException;
39
import org.apache.tools.ant.Project;
K
kohsuke 已提交
40 41
import org.apache.tools.ant.taskdefs.Chmod;
import org.apache.tools.ant.taskdefs.Copy;
42
import org.apache.tools.ant.types.FileSet;
43 44
import org.jruby.ext.posix.FileStat;
import org.jruby.ext.posix.POSIX;
45
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
46
import org.kohsuke.stapler.Stapler;
K
kohsuke 已提交
47

48 49
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
50
import java.io.*;
K
kohsuke 已提交
51
import java.net.InetAddress;
52 53
import java.net.URI;
import java.net.URISyntaxException;
54
import java.net.UnknownHostException;
55
import java.nio.ByteBuffer;
56 57
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
58
import java.nio.charset.Charset;
59
import java.nio.charset.CharsetEncoder;
60 61 62
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
63 64
import java.text.NumberFormat;
import java.text.ParseException;
65
import java.util.*;
K
kohsuke 已提交
66
import java.util.logging.Level;
K
kohsuke 已提交
67
import java.util.logging.Logger;
K
kohsuke 已提交
68 69 70
import java.util.regex.Matcher;
import java.util.regex.Pattern;

71
import static hudson.util.jna.GNUCLibrary.LIBC;
K
kohsuke 已提交
72

K
kohsuke 已提交
73
/**
K
kohsuke 已提交
74 75
 * Various utility methods that don't have more proper home.
 *
K
kohsuke 已提交
76 77 78
 * @author Kohsuke Kawaguchi
 */
public class Util {
K
kohsuke 已提交
79

80 81 82 83 84 85 86 87
    // 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 已提交
88 89
    /**
     * Creates a filtered sublist.
90
     * @since 1.176
K
kohsuke 已提交
91
     */
92
    public static <T> List<T> filter( Iterable<?> base, Class<T> type ) {
K
kohsuke 已提交
93 94 95 96 97 98 99 100
        List<T> r = new ArrayList<T>();
        for (Object i : base) {
            if(type.isInstance(i))
                r.add(type.cast(i));
        }
        return r;
    }

101 102 103 104 105 106 107
    /**
     * Creates a filtered sublist.
     */
    public static <T> List<T> filter( List<?> base, Class<T> type ) {
        return filter((Iterable)base,type);
    }

108 109 110
    /**
     * Pattern for capturing variables. Either $xyz or ${xyz}, while ignoring "$$"
      */
111
    private static final Pattern VARIABLE = Pattern.compile("\\$([A-Za-z0-9_]+|\\{[A-Za-z0-9_]+\\}|\\$)");
112

K
kohsuke 已提交
113
    /**
K
kohsuke 已提交
114
     * Replaces the occurrence of '$key' by <tt>properties.get('key')</tt>.
K
kohsuke 已提交
115 116
     *
     * <p>
117
     * Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
118
     *
K
kohsuke 已提交
119 120
     */
    public static String replaceMacro(String s, Map<String,String> properties) {
K
kohsuke 已提交
121 122
        return replaceMacro(s,new VariableResolver.ByMap<String>(properties));
    }
123
    
K
kohsuke 已提交
124 125 126 127 128 129 130
    /**
     * 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.)
     */
    public static String replaceMacro(String s, VariableResolver<String> resolver) {
131 132 133 134
    	if (s == null) {
    		return null;
    	}
    	
K
kohsuke 已提交
135
        int idx=0;
136 137 138 139 140 141
        while(true) {
            Matcher m = VARIABLE.matcher(s);
            if(!m.find(idx))   return s;

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

142 143 144 145 146 147 148 149 150
            // 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);
            }

151
            if(value==null)
152
                idx = m.end(); // skip this
153 154
            else {
                s = s.substring(0,m.start())+value+s.substring(m.end());
155
                idx = m.start() + value.length();
K
kohsuke 已提交
156 157 158 159
            }
        }
    }

K
kohsuke 已提交
160 161 162 163
    /**
     * Loads the contents of a file into a string.
     */
    public static String loadFile(File logfile) throws IOException {
164 165 166 167
        return loadFile(logfile, Charset.defaultCharset());
    }

    public static String loadFile(File logfile,Charset charset) throws IOException {
K
kohsuke 已提交
168 169 170
        if(!logfile.exists())
            return "";

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

173
        BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(logfile),charset));
174 175 176 177 178 179 180 181
        try {
            char[] buf = new char[1024];
            int len;
            while((len=r.read(buf,0,buf.length))>0)
               str.append(buf,0,len);
        } finally {
            r.close();
        }
K
kohsuke 已提交
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

        return str.toString();
    }

    /**
     * Deletes the contents of the given directory (but not the directory itself)
     * recursively.
     *
     * @throws IOException
     *      if the operation fails.
     */
    public static void deleteContentsRecursive(File file) throws IOException {
        File[] files = file.listFiles();
        if(files==null)
            return;     // the directory didn't exist in the first place
197 198
        for (File child : files)
            deleteRecursive(child);
K
kohsuke 已提交
199 200
    }

201 202 203 204 205 206
    /**
     * Deletes this file (and does not take no for an answer).
     * @param f a file to delete
     * @throws IOException if it exists but could not be successfully deleted
     */
    public static void deleteFile(File f) throws IOException {
K
kohsuke 已提交
207 208 209 210 211 212
        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?
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
            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());
229

K
kohsuke 已提交
230 231 232 233 234 235 236
            if(!f.delete() && f.exists()) {
                // trouble-shooting.
                // see http://www.nabble.com/Sometimes-can%27t-delete-files-from-hudson.scm.SubversionSCM%24CheckOutTask.invoke%28%29-tt17333292.html
                // 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));
237
                throw new IOException("Unable to delete " + f.getPath());
K
kohsuke 已提交
238
            }
K
kohsuke 已提交
239 240 241
        }
    }

242
    /**
243
     * Makes the given file writable by any means possible.
244
     */
K
kohsuke 已提交
245
    @IgnoreJRERequirement
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    private static void makeWritable(File f) {
        // 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);
        }

        // also try JDK6-way of doing it.
        try {
            f.setWritable(true);
        } catch (NoSuchMethodError e) {
            // not JDK6
        }
264 265 266 267 268 269 270 271 272 273

        try {// try libc chmod
            POSIX posix = PosixAPI.get();
            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);
        }

274 275
    }

K
kohsuke 已提交
276
    public static void deleteRecursive(File dir) throws IOException {
277 278
        if(!isSymlink(dir))
            deleteContentsRecursive(dir);
279 280 281 282 283 284 285 286 287 288
        try {
            deleteFile(dir);
        } catch (IOException e) {
            // if some of the child directories are big, it might take long enough to delete that
            // it allows others to create new files, causing problemsl ike JENKINS-10113
            // so give it one more attempt before we give up.
            if(!isSymlink(dir))
                deleteContentsRecursive(dir);
            deleteFile(dir);
        }
K
kohsuke 已提交
289 290
    }

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    /*
     * 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
310
    public static boolean isSymlink(File file) throws IOException {
311 312 313
        String name = file.getName();
        if (name.equals(".") || name.equals(".."))
            return false;
314

315
        File fileInCanonicalParent;
316 317 318 319 320 321 322
        File parentDir = file.getParentFile();
        if ( parentDir == null ) {
            fileInCanonicalParent = file;
        } else {
            fileInCanonicalParent = new File( parentDir.getCanonicalPath(), name );
        }
        return !fileInCanonicalParent.getCanonicalFile().equals( fileInCanonicalParent.getAbsoluteFile() );
323
    }
324

K
kohsuke 已提交
325 326 327 328 329 330 331 332 333 334 335 336
    /**
     * Creates a new temporary directory.
     */
    public static File createTempDir() throws IOException {
        File tmp = File.createTempFile("hudson", "tmp");
        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;
    }

337
    private static final Pattern errorCodeParser = Pattern.compile(".*CreateProcess.*error=([0-9]+).*");
K
kohsuke 已提交
338 339 340 341 342

    /**
     * On Windows, error messages for IOException aren't very helpful.
     * This method generates additional user-friendly error message to the listener
     */
K
kohsuke 已提交
343 344 345 346 347 348
    public static void displayIOException( IOException e, TaskListener listener ) {
        String msg = getWin32ErrorMessage(e);
        if(msg!=null)
            listener.getLogger().println(msg);
    }

349 350 351 352
    public static String getWin32ErrorMessage(IOException e) {
        return getWin32ErrorMessage((Throwable)e);
    }

K
kohsuke 已提交
353
    /**
354
     * Extracts the Win32 error message from {@link Throwable} if possible.
K
kohsuke 已提交
355 356 357 358
     *
     * @return
     *      null if there seems to be no error code or if the platform is not Win32.
     */
359
    public static String getWin32ErrorMessage(Throwable e) {
K
kohsuke 已提交
360
        String msg = e.getMessage();
361 362 363 364 365 366 367 368 369 370
        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
                }
            }
371
        }
K
kohsuke 已提交
372

373 374 375
        if(e.getCause()!=null)
            return getWin32ErrorMessage(e.getCause());
        return null; // no message
K
kohsuke 已提交
376 377
    }

378
    /**
379
     * Gets a human readable message for the given Win32 error code.
380 381 382 383 384
     *
     * @return
     *      null if no such message is available.
     */
    public static String getWin32ErrorMessage(int n) {
385 386 387 388 389 390 391
        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;
        }
392 393
    }

K
kohsuke 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407
    /**
     * Guesses the current host name.
     */
    public static String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            return "localhost";
        }
    }

    public static void copyStream(InputStream in,OutputStream out) throws IOException {
        byte[] buf = new byte[8192];
        int len;
K
kohsuke 已提交
408 409 410 411 412 413 414
        while((len=in.read(buf))>0)
            out.write(buf,0,len);
    }

    public static void copyStream(Reader in, Writer out) throws IOException {
        char[] buf = new char[8192];
        int len;
K
kohsuke 已提交
415 416 417 418
        while((len=in.read(buf))>0)
            out.write(buf,0,len);
    }

K
kohsuke 已提交
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    public static void copyStreamAndClose(InputStream in,OutputStream out) throws IOException {
        try {
            copyStream(in,out);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }

    public static void copyStreamAndClose(Reader in,Writer out) throws IOException {
        try {
            copyStream(in,out);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }

K
kohsuke 已提交
437
    /**
K
kohsuke 已提交
438 439 440 441 442 443
     * 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 已提交
444
     * @since 1.145
K
kohsuke 已提交
445
     * @see QuotedStringTokenizer
K
kohsuke 已提交
446 447
     */
    public static String[] tokenize(String s,String delimiter) {
K
kohsuke 已提交
448
        return QuotedStringTokenizer.tokenize(s,delimiter);
K
kohsuke 已提交
449 450
    }

K
kohsuke 已提交
451 452 453 454
    public static String[] tokenize(String s) {
        return tokenize(s," \t\n\r\f");
    }

455 456 457
    /**
     * Converts the map format of the environment variables to the K=V format in the array.
     */
J
jglick 已提交
458
    public static String[] mapToEnv(Map<String,String> m) {
K
kohsuke 已提交
459 460 461
        String[] r = new String[m.size()];
        int idx=0;

J
jglick 已提交
462 463
        for (final Map.Entry<String,String> e : m.entrySet()) {
            r[idx++] = e.getKey() + '=' + e.getValue();
K
kohsuke 已提交
464 465 466 467 468 469 470 471 472 473 474 475 476
        }
        return r;
    }

    public static int min(int x, int... values) {
        for (int i : values) {
            if(i<x)
                x=i;
        }
        return x;
    }

    public static String nullify(String v) {
K
Kohsuke Kawaguchi 已提交
477
        return fixEmpty(v);
K
kohsuke 已提交
478 479
    }

K
kohsuke 已提交
480 481 482 483 484
    public static String removeTrailingSlash(String s) {
        if(s.endsWith("/")) return s.substring(0,s.length()-1);
        else                return s;
    }

K
kohsuke 已提交
485 486 487 488 489
    /**
     * 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 已提交
490 491
     * @return
     *      32-char wide string
K
kohsuke 已提交
492 493 494 495 496
     */
    public static String getDigestOf(InputStream source) throws IOException {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");

497
            byte[] buffer = new byte[1024];
K
kohsuke 已提交
498 499
            DigestInputStream in =new DigestInputStream(source,md5);
            try {
500
                while(in.read(buffer)>0)
K
kohsuke 已提交
501 502 503 504 505 506 507 508 509
                    ; // simply discard the input
            } finally {
                in.close();
            }
            return toHexString(md5.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new IOException2("MD5 not installed",e);    // impossible
        }
    }
510

511 512
    public static String getDigestOf(String text) {
        try {
K
kohsuke 已提交
513
            return getDigestOf(new ByteArrayInputStream(text.getBytes("UTF-8")));
514 515 516 517
        } catch (IOException e) {
            throw new Error(e);
        }
    }
K
kohsuke 已提交
518

519
    /**
520
     * Converts a string into 128-bit AES key.
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
     * @since 1.308
     */
    public static SecretKey toAes128Key(String s) {
        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);
        }
    }

K
kohsuke 已提交
539
    public static String toHexString(byte[] data, int start, int len) {
540
        StringBuilder buf = new StringBuilder();
K
kohsuke 已提交
541 542 543 544 545 546 547 548 549 550 551 552
        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();
    }

    public static String toHexString(byte[] bytes) {
        return toHexString(bytes,0,bytes.length);
    }

K
kohsuke 已提交
553 554 555 556 557 558 559
    public static byte[] fromHexString(String data) {
        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 已提交
560
    /**
K
kohsuke 已提交
561
     * Returns a human readable text of the time duration, for example "3 minutes 40 seconds".
K
i18n  
kohsuke 已提交
562
     * This version should be used for representing a duration of some activity (like build)
K
kohsuke 已提交
563 564 565 566
     *
     * @param duration
     *      number of milliseconds.
     */
K
kohsuke 已提交
567
    public static String getTimeSpanString(long duration) {
568 569 570 571 572 573 574 575 576 577 578 579
        // 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;
580 581
        duration %= ONE_SECOND_MS;
        long millisecs = duration;
582 583

        if (years > 0)
C
cactusman 已提交
584
            return makeTimeSpanString(years, Messages.Util_year(years), months, Messages.Util_month(months));
585
        else if (months > 0)
C
cactusman 已提交
586
            return makeTimeSpanString(months, Messages.Util_month(months), days, Messages.Util_day(days));
587
        else if (days > 0)
C
cactusman 已提交
588
            return makeTimeSpanString(days, Messages.Util_day(days), hours, Messages.Util_hour(hours));
589
        else if (hours > 0)
C
cactusman 已提交
590
            return makeTimeSpanString(hours, Messages.Util_hour(hours), minutes, Messages.Util_minute(minutes));
591
        else if (minutes > 0)
C
cactusman 已提交
592
            return makeTimeSpanString(minutes, Messages.Util_minute(minutes), seconds, Messages.Util_second(seconds));
593
        else if (seconds >= 10)
C
cactusman 已提交
594
            return Messages.Util_second(seconds);
595
        else if (seconds >= 1)
596
            return Messages.Util_second(seconds+(float)(millisecs/100)/10); // render "1.2 sec"
597
        else if(millisecs>=100)
598
            return Messages.Util_second((float)(millisecs/10)/100); // render "0.12 sec".
599 600
        else
            return Messages.Util_millisecond(millisecs);
K
kohsuke 已提交
601 602
    }

603 604

    /**
605
     * Create a string representation of a time duration.  If the quantity of
606
     * the most significant unit is big (>=10), then we use only that most
607
     * significant unit in the string representation. If the quantity of the
608 609 610 611 612 613 614 615 616
     * 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".
     */
    private static String makeTimeSpanString(long bigUnit,
                                             String bigLabel,
                                             long smallUnit,
                                             String smallLabel) {
C
cactusman 已提交
617
        String text = bigLabel;
618
        if (bigUnit < 10)
C
cactusman 已提交
619
            text += ' ' + smallLabel;
620 621 622 623
        return text;
    }


K
i18n  
kohsuke 已提交
624 625
    /**
     * Get a human readable string representing strings like "xxx days ago",
626
     * which should be used to point to the occurrence of an event in the past.
K
i18n  
kohsuke 已提交
627 628 629 630 631
     */
    public static String getPastTimeString(long duration) {
        return Messages.Util_pastTime(getTimeSpanString(duration));
    }

632

K
kohsuke 已提交
633
    /**
K
kohsuke 已提交
634
     * Combines number and unit, with a plural suffix if needed.
635 636 637
     * 
     * @deprecated 
     *   Use individual localization methods instead. 
638
     *   See {@link Messages#Util_year(Object)} for an example.
639
     *   Deprecated since 2009-06-24, remove method after 2009-12-24.
K
kohsuke 已提交
640 641 642 643
     */
    public static String combine(long n, String suffix) {
        String s = Long.toString(n)+' '+suffix;
        if(n!=1)
644 645
        	// 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 已提交
646 647 648
        return s;
    }

K
kohsuke 已提交
649 650 651 652 653 654 655 656 657 658 659 660
    /**
     * Create a sub-list by only picking up instances of the specified type.
     */
    public static <T> List<T> createSubList( Collection<?> source, Class<T> type ) {
        List<T> r = new ArrayList<T>();
        for (Object item : source) {
            if(type.isInstance(item))
                r.add(type.cast(item));
        }
        return r;
    }

K
kohsuke 已提交
661
    /**
K
kohsuke 已提交
662
     * Escapes non-ASCII characters in URL.
663 664 665 666 667
     *
     * <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
668
     * a single path component to that method (it will encode /, but this method does not).
K
kohsuke 已提交
669 670 671 672 673
     */
    public static String encode(String s) {
        try {
            boolean escaped = false;

674
            StringBuilder out = new StringBuilder(s.length());
K
kohsuke 已提交
675 676 677 678 679

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

            for (int i = 0; i < s.length(); i++) {
680
                int c = s.charAt(i);
K
kohsuke 已提交
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
                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
        }
    }

703 704 705 706 707 708 709 710 711 712
    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++)
L
lvotypko 已提交
713
            uriMap[i] = (raw.charAt(j) == ' ' || raw.charAt(j) =='&');
714 715 716 717
        // If we add encodeQuery() just add a 2nd map to encode &+=
        // queryMap[38] = queryMap[43] = queryMap[61] = true;
    }

718 719 720
    /**
     * Encode a single path component for use in an HTTP URL.
     * Escapes all non-ASCII, general unsafe (space and "#%<>[\]^`{|}~)
721 722
     * and HTTP special characters (/;:?) as specified in RFC1738.
     * (so alphanumeric and !@$&*()-_=+',. are not encoded)
723 724
     * Note that slash(/) is encoded, so the given string should be a
     * single path component used in constructing a URL.
725
     * Method name inspired by PHP's rawurlencode.
726 727 728 729 730 731 732 733 734
     */
    public static String rawEncode(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++) {
            c = s.charAt(i);
735
            if (c > 122 || uriMap[c]) {
736 737 738 739 740 741 742 743 744 745 746
                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 {
747 748 749
                    ByteBuffer bytes = enc.encode(buf);
                    while (bytes.hasRemaining()) {
                        byte b = bytes.get();
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
                        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 已提交
766 767 768 769 770 771 772
    /**
     * Surrounds by a single-quote.
     */
    public static String singleQuote(String s) {
        return '\''+s+'\'';
    }

773
    /**
774
     * Escapes HTML unsafe characters like &lt;, &amp; to the respective character entities.
775 776
     */
    public static String escape(String text) {
K
kohsuke 已提交
777
        if (text==null)     return null;
778
        StringBuilder buf = new StringBuilder(text.length()+64);
779 780 781 782 783 784 785 786 787 788 789
        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
            if(ch=='&')
                buf.append("&amp;");
            else
S
Seiji Sogabe 已提交
790 791 792 793 794 795
            if(ch=='"')
                buf.append("&quot;");
            else
            if(ch=='\'')
                buf.append("&#039;");
            else
796 797 798 799 800 801 802 803
            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
804 805 806 807 808
                buf.append(ch);
        }
        return buf.toString();
    }

K
kohsuke 已提交
809
    public static String xmlEscape(String text) {
810
        StringBuilder buf = new StringBuilder(text.length()+64);
K
kohsuke 已提交
811 812 813 814 815 816 817 818 819 820 821 822 823
        for( int i=0; i<text.length(); i++ ) {
            char ch = text.charAt(i);
            if(ch=='<')
                buf.append("&lt;");
            else
            if(ch=='&')
                buf.append("&amp;");
            else
                buf.append(ch);
        }
        return buf.toString();
    }

K
kohsuke 已提交
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
    /**
     * Creates an empty file.
     */
    public static void touch(File file) throws IOException {
        new FileOutputStream(file).close();
    }

    /**
     * Copies a single file by using Ant.
     */
    public static void copyFile(File src, File dst) throws BuildException {
        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 "".
     */
    public static String fixNull(String s) {
        if(s==null)     return "";
        else            return s;
    }

    /**
     * Convert empty string to null.
     */
    public static String fixEmpty(String s) {
        if(s==null || s.length()==0)    return null;
        return s;
    }

K
kohsuke 已提交
859 860 861 862 863 864 865
    /**
     * Convert empty string to null, and trim whitespace.
     *
     * @since 1.154
     */
    public static String fixEmptyAndTrim(String s) {
        if(s==null)    return null;
K
kohsuke 已提交
866
        return fixEmpty(s.trim());
K
kohsuke 已提交
867 868
    }

869 870 871 872 873 874 875 876
    public static <T> List<T> fixNull(List<T> l) {
        return l!=null ? l : Collections.<T>emptyList();
    }

    public static <T> Set<T> fixNull(Set<T> l) {
        return l!=null ? l : Collections.<T>emptySet();
    }

877 878 879 880
    public static <T> Collection<T> fixNull(Collection<T> l) {
        return l!=null ? l : Collections.<T>emptySet();
    }

K
kohsuke 已提交
881 882 883 884
    public static <T> Iterable<T> fixNull(Iterable<T> l) {
        return l!=null ? l : Collections.<T>emptySet();
    }

K
kohsuke 已提交
885 886 887 888 889 890 891 892 893 894 895 896 897
    /**
     * Cuts all the leading path portion and get just the file name.
     */
    public static String getFileName(String filePath) {
        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 已提交
898 899 900
    /**
     * Concatenate multiple strings by inserting a separator.
     */
901
    public static String join(Collection<?> strings, String separator) {
K
kohsuke 已提交
902 903
        StringBuilder buf = new StringBuilder();
        boolean first=true;
904
        for (Object s : strings) {
K
kohsuke 已提交
905
            if(first)   first=false;
906
            else        buf.append(separator);
K
kohsuke 已提交
907 908 909 910 911
            buf.append(s);
        }
        return buf.toString();
    }

K
kohsuke 已提交
912 913 914 915 916 917 918 919 920 921 922 923 924
    /**
     * Combines all the given collections into a single list.
     */
    public static <T> List<T> join(Collection<? extends T>... items) {
        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;
    }

925 926 927 928 929 930 931 932 933 934 935 936
    /**
     * 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 已提交
937
     * @param excludes
K
kohsuke 已提交
938 939
     *      Exclusion pattern. Follows the same format as the 'includes' parameter.
     *      Can be null.
K
kohsuke 已提交
940
     * @since 1.172
941
     */
K
kohsuke 已提交
942
    public static FileSet createFileSet(File baseDir, String includes, String excludes) {
943 944 945
        FileSet fs = new FileSet();
        fs.setDir(baseDir);
        fs.setProject(new Project());
K
kohsuke 已提交
946 947 948 949

        StringTokenizer tokens;

        tokens = new StringTokenizer(includes,",");
950 951 952 953
        while(tokens.hasMoreTokens()) {
            String token = tokens.nextToken().trim();
            fs.createInclude().setName(token);
        }
K
kohsuke 已提交
954 955 956 957 958 959 960
        if(excludes!=null) {
            tokens = new StringTokenizer(excludes,",");
            while(tokens.hasMoreTokens()) {
                String token = tokens.nextToken().trim();
                fs.createExclude().setName(token);
            }
        }
961 962
        return fs;
    }
K
kohsuke 已提交
963

K
kohsuke 已提交
964 965 966 967
    public static FileSet createFileSet(File baseDir, String includes) {
        return createFileSet(baseDir,includes,null);
    }

968 969 970 971
    /**
     * Creates a symlink to baseDir+targetPath at baseDir+symlinkPath.
     * <p>
     * If there's a prior symlink at baseDir+symlinkPath, it will be overwritten.
972 973 974 975 976 977 978
     *
     * @param baseDir
     *      Base directory to resolve the 'symlinkPath' parameter.
     * @param targetPath
     *      The file that the symlink should point to.
     * @param symlinkPath
     *      Where to create a symlink in.
979 980
     */
    public static void createSymlink(File baseDir, String targetPath, String symlinkPath, TaskListener listener) throws InterruptedException {
981
        if(Functions.isWindows() || NO_SYMLINK)   return;
K
kohsuke 已提交
982 983

        try {
984
            String errmsg = "";
K
kohsuke 已提交
985 986 987 988 989 990 991 992
            // 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.
            File symlinkFile = new File(baseDir, symlinkPath);
            if (!symlinkFile.delete() && symlinkFile.exists())
                // ignore a failure.
                new LocalProc(new String[]{"rm","-rf", symlinkPath},new String[0],listener.getLogger(), baseDir).join();

993
            Integer r=null;
K
kohsuke 已提交
994 995
            if (!SYMLINK_ESCAPEHATCH) {
                try {
996 997
                    r = LIBC.symlink(targetPath,symlinkFile.getAbsolutePath());
                    if (r!=0) {
K
kohsuke 已提交
998
                        r = Native.getLastError();
999 1000
                        errmsg = LIBC.strerror(r);
                    }
K
kohsuke 已提交
1001 1002 1003
                } catch (LinkageError e) {
                    // if JNA is unavailable, fall back.
                    // we still prefer to try JNA first as PosixAPI supports even smaller platforms.
1004
                    if (PosixAPI.supportsNative()) {
1005 1006
                        r = PosixAPI.get().symlink(targetPath,symlinkFile.getAbsolutePath());
                    }
K
kohsuke 已提交
1007
                }
1008
            }
1009 1010
            if (r==null) {
                // if all else fail, fall back to the most expensive approach of forking a process
K
kohsuke 已提交
1011 1012 1013
                r = new LocalProc(new String[]{
                    "ln","-s", targetPath, symlinkPath},
                    new String[0],listener.getLogger(), baseDir).join();
1014
            }
1015
            if (r!=0)
1016
                listener.getLogger().println(String.format("ln -s %s %s failed: %d %s",targetPath, symlinkFile, r, errmsg));
K
kohsuke 已提交
1017 1018
        } catch (IOException e) {
            PrintStream log = listener.getLogger();
1019
            log.printf("ln %s %s failed%n",targetPath, new File(baseDir, symlinkPath));
K
kohsuke 已提交
1020 1021 1022 1023 1024
            Util.displayIOException(e,listener);
            e.printStackTrace( log );
        }
    }

K
Kohsuke Kawaguchi 已提交
1025 1026 1027 1028 1029 1030 1031 1032
    /**
     * @deprecated as of 1.456
     *      Use {@link #resolveSymlink(File)}
     */
    public static String resolveSymlink(File link, TaskListener listener) throws InterruptedException, IOException {
        return resolveSymlink(link);
    }

K
kohsuke 已提交
1033 1034 1035 1036 1037 1038 1039 1040
    /**
     * Resolves symlink, if the given file is a symlink. Otherwise return null.
     * <p>
     * If the resolution fails, report an error.
     *
     * @param listener
     *      If we rely on an external command to resolve symlink, this is it.
     */
K
Kohsuke Kawaguchi 已提交
1041
    public static String resolveSymlink(File link) throws InterruptedException, IOException {
1042
        if(Functions.isWindows())     return null;
K
kohsuke 已提交
1043 1044 1045 1046 1047

        String filename = link.getAbsolutePath();
        try {
            for (int sz=512; sz < 65536; sz*=2) {
                Memory m = new Memory(sz);
1048
                int r = LIBC.readlink(filename,m,new NativeLong(sz));
K
kohsuke 已提交
1049
                if (r<0) {
K
bug fix  
kohsuke 已提交
1050 1051
                    int err = Native.getLastError();
                    if (err==22/*EINVAL --- but is this really portable?*/)
K
kohsuke 已提交
1052
                        return null; // this means it's not a symlink
1053
                    throw new IOException("Failed to readlink "+link+" error="+ err+" "+ LIBC.strerror(err));
K
kohsuke 已提交
1054 1055 1056 1057 1058 1059 1060
                }
                if (r==sz)
                    continue;   // buffer too small

                byte[] buf = new byte[r];
                m.read(0,buf,0,r);
                return new String(buf);
1061
            }
K
kohsuke 已提交
1062 1063 1064 1065 1066 1067
            // something is wrong. It can't be this long!
            throw new IOException("Symlink too long: "+link);
        } catch (LinkageError e) {
            // if JNA is unavailable, fall back.
            // we still prefer to try JNA first as PosixAPI supports even smaller platforms.
            return PosixAPI.get().readlink(filename);
1068 1069 1070
        }
    }

1071 1072 1073 1074 1075 1076 1077
    /**
     * 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 已提交
1078
     * @deprecated since 2008-05-13. This method is broken (see ISSUE#1666). It should probably
1079 1080 1081
     * be removed but I'm not sure if it is considered part of the public API
     * that needs to be maintained for backwards compatibility.
     * Use {@link #encode(String)} instead. 
1082
     */
1083
    @Deprecated
1084 1085 1086 1087 1088 1089 1090 1091 1092
    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 已提交
1093 1094
    /**
     * Wraps with the error icon and the CSS class to render error message.
1095
     * @since 1.173
K
kohsuke 已提交
1096 1097 1098
     */
    public static String wrapToErrorSpan(String s) {
        s = "<span class=error><img src='"+
1099
            Stapler.getCurrentRequest().getContextPath()+ Jenkins.RESOURCE_PATH+
K
kohsuke 已提交
1100 1101 1102
            "/images/none.gif' height=16 width=1>"+s+"</span>";
        return s;
    }
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
    
    /**
     * 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
     */
    public static Number tryParseNumber(String numberStr, Number defaultNumber) {
        if ((numberStr == null) || (numberStr.length() == 0)) {
            return defaultNumber;
        }
        try {
            return NumberFormat.getNumberInstance().parse(numberStr);
        } catch (ParseException e) {
            return defaultNumber;
        }
    }
K
kohsuke 已提交
1122

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
    /**
     * Checks if the public method defined on the base type with the given arguments
     * are overridden in the given derived type.
     */
    public static boolean isOverridden(Class base, Class derived, String methodName, Class... types) {
        // the rewriteHudsonWar method isn't overridden.
        try {
            return !base.getMethod(methodName, types).equals(
                    derived.getMethod(methodName,types));
        } catch (NoSuchMethodException e) {
            throw new AssertionError(e);
        }
    }

1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
    /**
     * Returns a file name by changing its extension.
     *
     * @param ext
     *      For example, ".zip"
     */
    public static File changeExtension(File dst, String ext) {
        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 已提交
1150 1151 1152 1153 1154 1155 1156
    /**
     * Null-safe String intern method.
     */
    public static String intern(String s) {
        return s==null ? s : s.intern();
    }

1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
    /**
     * Loads a key/value pair string as {@link Properties}
     * @since 1.392
     */
    @IgnoreJRERequirement
    public static Properties loadProperties(String properties) throws IOException {
        Properties p = new Properties();
        try {
            p.load(new StringReader(properties));
        } catch (NoSuchMethodError e) {
            // load(Reader) method is only available on JDK6.
            // this fall back version doesn't work correctly with non-ASCII characters,
            // but there's no other easy ways out it seems.
            p.load(new ByteArrayInputStream(properties.getBytes()));
        }
        return p;
    }

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

1177
    // Note: RFC822 dates must not be localized!
1178 1179
    public static final FastDateFormat RFC822_DATETIME_FORMATTER
            = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
K
kohsuke 已提交
1180 1181

    private static final Logger LOGGER = Logger.getLogger(Util.class.getName());
1182 1183 1184 1185 1186

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

    public static boolean SYMLINK_ESCAPEHATCH = Boolean.getBoolean(Util.class.getName()+".symlinkEscapeHatch");
K
kohsuke 已提交
1189
}