Util.java 25.8 KB
Newer Older
K
kohsuke 已提交
1 2
package hudson;

K
kohsuke 已提交
3
import hudson.model.TaskListener;
K
kohsuke 已提交
4
import hudson.model.Hudson;
5
import static hudson.model.Hudson.isWindows;
K
kohsuke 已提交
6
import hudson.util.IOException2;
K
kohsuke 已提交
7
import hudson.util.QuotedStringTokenizer;
8
import hudson.Proc.LocalProc;
K
kohsuke 已提交
9
import org.apache.tools.ant.BuildException;
10 11
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
K
kohsuke 已提交
12 13
import org.apache.tools.ant.taskdefs.Chmod;
import org.apache.tools.ant.taskdefs.Copy;
K
kohsuke 已提交
14
import org.kohsuke.stapler.Stapler;
K
kohsuke 已提交
15 16

import java.io.BufferedReader;
17
import java.io.ByteArrayInputStream;
K
kohsuke 已提交
18 19 20 21 22 23 24 25
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
K
kohsuke 已提交
26 27
import java.io.Reader;
import java.io.Writer;
28
import java.io.PrintStream;
K
kohsuke 已提交
29 30
import java.net.InetAddress;
import java.net.UnknownHostException;
31 32
import java.net.URI;
import java.net.URISyntaxException;
33 34 35
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
36 37
import java.text.NumberFormat;
import java.text.ParseException;
K
kohsuke 已提交
38
import java.text.SimpleDateFormat;
39 40 41
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
42
import java.util.Locale;
K
kohsuke 已提交
43 44 45
import java.util.Map;
import java.util.ResourceBundle;
import java.util.SimpleTimeZone;
K
kohsuke 已提交
46
import java.util.StringTokenizer;
K
kohsuke 已提交
47
import java.util.logging.Level;
K
kohsuke 已提交
48
import java.util.logging.Logger;
K
kohsuke 已提交
49 50 51 52
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
K
kohsuke 已提交
53 54
 * Various utility methods that don't have more proper home.
 *
K
kohsuke 已提交
55 56 57
 * @author Kohsuke Kawaguchi
 */
public class Util {
K
kohsuke 已提交
58

59 60 61 62 63 64 65 66
    // 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 已提交
67 68
    /**
     * Creates a filtered sublist.
69
     * @since 1.176
K
kohsuke 已提交
70
     */
71
    public static <T> List<T> filter( Iterable<?> base, Class<T> type ) {
K
kohsuke 已提交
72 73 74 75 76 77 78 79
        List<T> r = new ArrayList<T>();
        for (Object i : base) {
            if(type.isInstance(i))
                r.add(type.cast(i));
        }
        return r;
    }

80 81 82 83 84 85 86
    /**
     * Creates a filtered sublist.
     */
    public static <T> List<T> filter( List<?> base, Class<T> type ) {
        return filter((Iterable)base,type);
    }

87 88 89 90 91
    /**
     * Pattern for capturing variables. Either $xyz or ${xyz}, while ignoring "$$"
      */
    private static final Pattern VARIABLE = Pattern.compile("(?<!\\$)\\$([A-Za-z0-9_]+|\\{[A-Za-z0-9_]+\\})");

K
kohsuke 已提交
92
    /**
K
kohsuke 已提交
93
     * Replaces the occurrence of '$key' by <tt>properties.get('key')</tt>.
K
kohsuke 已提交
94 95
     *
     * <p>
96
     * Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
97
     *
K
kohsuke 已提交
98 99 100
     */
    public static String replaceMacro(String s, Map<String,String> properties) {
        int idx=0;
101 102 103 104 105 106 107
        while(true) {
            Matcher m = VARIABLE.matcher(s);
            if(!m.find(idx))   return s;

            String key = m.group().substring(1);
            if(key.charAt(0)=='{')  key = key.substring(1,key.length()-1);

K
kohsuke 已提交
108
            String value = properties.get(key);
109 110 111 112 113
            if(value==null)
                idx = m.start()+1; // skip this
            else {
                s = s.substring(0,m.start())+value+s.substring(m.end());
                idx = m.start();
K
kohsuke 已提交
114 115 116 117
            }
        }
    }

K
kohsuke 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    /**
     * Loads the contents of a file into a string.
     */
    public static String loadFile(File logfile) throws IOException {
        if(!logfile.exists())
            return "";

        StringBuffer str = new StringBuffer((int)logfile.length());

        BufferedReader r = new BufferedReader(new FileReader(logfile));
        char[] buf = new char[1024];
        int len;
        while((len=r.read(buf,0,buf.length))>0)
           str.append(buf,0,len);
        r.close();

        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
148 149
        for (File child : files)
            deleteRecursive(child);
K
kohsuke 已提交
150 151 152 153 154 155 156 157 158
    }

    private static void deleteFile(File f) throws IOException {
        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?
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
            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());
175

176 177
            if(!f.delete() && f.exists())
                throw new IOException("Unable to delete " + f.getPath());
K
kohsuke 已提交
178 179 180
        }
    }

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    /**
     * Makes the given file writable.
     */
    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
        }
    }

K
kohsuke 已提交
204
    public static void deleteRecursive(File dir) throws IOException {
205 206
        if(!isSymlink(dir))
            deleteContentsRecursive(dir);
K
kohsuke 已提交
207 208 209
        deleteFile(dir);
    }

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    /*
     * 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
229
    public static boolean isSymlink(File file) throws IOException {
230 231 232 233 234 235 236 237 238
        File parent = file.getParentFile();
        File canonicalFile = file.getCanonicalFile();

        return parent != null
            && (!canonicalFile.getName().equals(file.getName()) || !canonicalFile.getPath().startsWith(
            parent.getCanonicalPath()));
    }


K
kohsuke 已提交
239 240 241 242 243 244 245 246 247 248 249 250
    /**
     * 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;
    }

251
    private static final Pattern errorCodeParser = Pattern.compile(".*CreateProcess.*error=([0-9]+).*");
K
kohsuke 已提交
252 253 254 255 256

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

263 264 265 266
    public static String getWin32ErrorMessage(IOException e) {
        return getWin32ErrorMessage((Throwable)e);
    }

K
kohsuke 已提交
267
    /**
268
     * Extracts the Win32 error message from {@link Throwable} if possible.
K
kohsuke 已提交
269 270 271 272
     *
     * @return
     *      null if there seems to be no error code or if the platform is not Win32.
     */
273
    public static String getWin32ErrorMessage(Throwable e) {
K
kohsuke 已提交
274
        String msg = e.getMessage();
275 276 277 278 279 280 281 282 283 284
        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
                }
            }
285
        }
K
kohsuke 已提交
286

287 288 289
        if(e.getCause()!=null)
            return getWin32ErrorMessage(e.getCause());
        return null; // no message
K
kohsuke 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    }

    /**
     * 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 已提交
306 307 308 309 310 311 312
        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 已提交
313 314 315 316
        while((len=in.read(buf))>0)
            out.write(buf,0,len);
    }

K
kohsuke 已提交
317
    /**
K
kohsuke 已提交
318 319 320 321 322 323
     * 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 已提交
324
     * @since 1.145
K
kohsuke 已提交
325
     * @see QuotedStringTokenizer
K
kohsuke 已提交
326 327
     */
    public static String[] tokenize(String s,String delimiter) {
K
kohsuke 已提交
328
        return QuotedStringTokenizer.tokenize(s,delimiter);
K
kohsuke 已提交
329 330
    }

K
kohsuke 已提交
331 332 333 334
    public static String[] tokenize(String s) {
        return tokenize(s," \t\n\r\f");
    }

J
jglick 已提交
335
    public static String[] mapToEnv(Map<String,String> m) {
K
kohsuke 已提交
336 337 338
        String[] r = new String[m.size()];
        int idx=0;

J
jglick 已提交
339 340
        for (final Map.Entry<String,String> e : m.entrySet()) {
            r[idx++] = e.getKey() + '=' + e.getValue();
K
kohsuke 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
        }
        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) {
        if(v!=null && v.length()==0)    v=null;
        return v;
    }

K
kohsuke 已提交
358 359 360 361 362
    public static String removeTrailingSlash(String s) {
        if(s.endsWith("/")) return s.substring(0,s.length()-1);
        else                return s;
    }

K
kohsuke 已提交
363 364 365 366 367 368 369 370 371 372
    /**
     * Write-only buffer.
     */
    private static final byte[] garbage = new byte[8192];

    /**
     * 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 已提交
373 374
     * @return
     *      32-char wide string
K
kohsuke 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
     */
    public static String getDigestOf(InputStream source) throws IOException {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");

            DigestInputStream in =new DigestInputStream(source,md5);
            try {
                while(in.read(garbage)>0)
                    ; // simply discard the input
            } finally {
                in.close();
            }
            return toHexString(md5.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new IOException2("MD5 not installed",e);    // impossible
        }
    }
392

393 394
    public static String getDigestOf(String text) {
        try {
K
kohsuke 已提交
395
            return getDigestOf(new ByteArrayInputStream(text.getBytes("UTF-8")));
396 397 398 399
        } catch (IOException e) {
            throw new Error(e);
        }
    }
K
kohsuke 已提交
400

K
kohsuke 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413 414
    public static String toHexString(byte[] data, int start, int len) {
        StringBuffer buf = new StringBuffer();
        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 已提交
415 416
    /**
     * Returns a human readable text of the time duration.
K
i18n  
kohsuke 已提交
417
     * This version should be used for representing a duration of some activity (like build)
K
kohsuke 已提交
418 419 420 421
     *
     * @param duration
     *      number of milliseconds.
     */
K
kohsuke 已提交
422
    public static String getTimeSpanString(long duration) {
423 424 425 426 427 428 429 430 431 432 433 434 435 436
        // 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;

        if (years > 0)
C
cactusman 已提交
437
            return makeTimeSpanString(years, Messages.Util_year(years), months, Messages.Util_month(months));
438
        else if (months > 0)
C
cactusman 已提交
439
            return makeTimeSpanString(months, Messages.Util_month(months), days, Messages.Util_day(days));
440
        else if (days > 0)
C
cactusman 已提交
441
            return makeTimeSpanString(days, Messages.Util_day(days), hours, Messages.Util_hour(hours));
442
        else if (hours > 0)
C
cactusman 已提交
443
            return makeTimeSpanString(hours, Messages.Util_hour(hours), minutes, Messages.Util_minute(minutes));
444
        else if (minutes > 0)
C
cactusman 已提交
445
            return makeTimeSpanString(minutes, Messages.Util_minute(minutes), seconds, Messages.Util_second(seconds));
446 447
        else
            // Durations less than a minute are only expressed in seconds (no ms).
C
cactusman 已提交
448
            return Messages.Util_second(seconds);
K
kohsuke 已提交
449 450
    }

451 452 453 454 455 456 457 458 459 460 461 462 463 464

    /**
     * Create a string representation of a time duration.  If the quanity of
     * the most significant unit is big (>=10), then we use only that most
     * significant unit in the string represenation. If the quantity of the
     * most significant unit is small (a single-digit value), then we also
     * use a secondary, smaller unit for increased precision.
     * So 13 minutes and 43 seconds returns just "13 minutes", but 3 minutes
     * and 43 seconds is "3 minutes 43 seconds".
     */
    private static String makeTimeSpanString(long bigUnit,
                                             String bigLabel,
                                             long smallUnit,
                                             String smallLabel) {
C
cactusman 已提交
465
        String text = bigLabel;
466
        if (bigUnit < 10)
C
cactusman 已提交
467
            text += ' ' + smallLabel;
468 469 470 471
        return text;
    }


K
i18n  
kohsuke 已提交
472 473
    /**
     * Get a human readable string representing strings like "xxx days ago",
474
     * which should be used to point to the occurence of an event in the past.
K
i18n  
kohsuke 已提交
475 476 477 478 479
     */
    public static String getPastTimeString(long duration) {
        return Messages.Util_pastTime(getTimeSpanString(duration));
    }

480

K
kohsuke 已提交
481
    /**
K
kohsuke 已提交
482
     * Combines number and unit, with a plural suffix if needed.
K
kohsuke 已提交
483 484 485 486
     */
    public static String combine(long n, String suffix) {
        String s = Long.toString(n)+' '+suffix;
        if(n!=1)
C
cactusman 已提交
487
            s += Messages.Util_countSuffix();
K
kohsuke 已提交
488 489 490
        return s;
    }

K
kohsuke 已提交
491 492 493 494 495 496 497 498 499 500 501 502
    /**
     * 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 已提交
503
    /**
K
kohsuke 已提交
504
     * Escapes non-ASCII characters in URL.
K
kohsuke 已提交
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
     */
    public static String encode(String s) {
        try {
            boolean escaped = false;

            StringBuffer out = new StringBuffer(s.length());

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

            for (int i = 0; i < s.length(); i++) {
                int c = (int) s.charAt(i);
                if (c<128 && c!=' ') {
                    out.append((char) c);
                } else {
                    // 1 char -> UTF8
                    w.write(c);
                    w.flush();
                    for (byte b : buf.toByteArray()) {
                        out.append('%');
                        out.append(toDigit((b >> 4) & 0xF));
                        out.append(toDigit(b & 0xF));
                    }
                    buf.reset();
                    escaped = true;
                }
            }

            return escaped ? out.toString() : s;
        } catch (IOException e) {
            throw new Error(e); // impossible
        }
    }

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
    /**
     * Escapes HTML unsafe characters like &lt;, &amp;to the respective character entities.
     */
    public static String escape(String text) {
        StringBuffer buf = new StringBuffer(text.length()+64);
        for( int i=0; i<text.length(); i++ ) {
            char ch = text.charAt(i);
            if(ch=='\n')
                buf.append("<br>");
            else
            if(ch=='<')
                buf.append("&lt;");
            else
            if(ch=='&')
                buf.append("&amp;");
            else
555 556 557 558 559 560 561 562
            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
563 564 565 566 567
                buf.append(ch);
        }
        return buf.toString();
    }

K
kohsuke 已提交
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
    public static String xmlEscape(String text) {
        StringBuffer buf = new StringBuffer(text.length()+64);
        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 已提交
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
    private static char toDigit(int n) {
        char ch = Character.forDigit(n,16);
        if(ch>='a')     ch = (char)(ch-'a'+'A');
        return ch;
    }

    /**
     * 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 已提交
624 625 626 627 628 629 630
    /**
     * Convert empty string to null, and trim whitespace.
     *
     * @since 1.154
     */
    public static String fixEmptyAndTrim(String s) {
        if(s==null)    return null;
K
kohsuke 已提交
631
        return fixEmpty(s.trim());
K
kohsuke 已提交
632 633
    }

K
kohsuke 已提交
634 635 636 637 638 639 640 641 642 643 644 645 646
    /**
     * 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 已提交
647 648 649 650 651 652 653 654 655 656 657 658 659 660
    /**
     * Concatenate multiple strings by inserting a separator.
     */
    public static String join(Collection<String> strings, String seprator) {
        StringBuilder buf = new StringBuilder();
        boolean first=true;
        for (String s : strings) {
            if(first)   first=false;
            else        buf.append(seprator);
            buf.append(s);
        }
        return buf.toString();
    }

661 662 663 664 665 666 667 668 669 670 671 672
    /**
     * 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 已提交
673
     * @param excludes
K
kohsuke 已提交
674 675
     *      Exclusion pattern. Follows the same format as the 'includes' parameter.
     *      Can be null.
K
kohsuke 已提交
676
     * @since 1.172
677
     */
K
kohsuke 已提交
678
    public static FileSet createFileSet(File baseDir, String includes, String excludes) {
679 680 681
        FileSet fs = new FileSet();
        fs.setDir(baseDir);
        fs.setProject(new Project());
K
kohsuke 已提交
682 683 684 685

        StringTokenizer tokens;

        tokens = new StringTokenizer(includes,",");
686 687 688 689
        while(tokens.hasMoreTokens()) {
            String token = tokens.nextToken().trim();
            fs.createInclude().setName(token);
        }
K
kohsuke 已提交
690 691 692 693 694 695 696
        if(excludes!=null) {
            tokens = new StringTokenizer(excludes,",");
            while(tokens.hasMoreTokens()) {
                String token = tokens.nextToken().trim();
                fs.createExclude().setName(token);
            }
        }
697 698
        return fs;
    }
K
kohsuke 已提交
699

K
kohsuke 已提交
700 701 702 703
    public static FileSet createFileSet(File baseDir, String includes) {
        return createFileSet(baseDir,includes,null);
    }

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
    /**
     * Creates a symlink to baseDir+targetPath at baseDir+symlinkPath.
     * <p>
     * If there's a prior symlink at baseDir+symlinkPath, it will be overwritten.
     */
    public static void createSymlink(File baseDir, String targetPath, String symlinkPath, TaskListener listener) throws InterruptedException {
        if(!isWindows()) {
            try {
                // ignore a failure.
                new LocalProc(new String[]{"rm","-rf", symlinkPath},new String[0],listener.getLogger(), baseDir).join();

                int r = new LocalProc(new String[]{
                    "ln","-s", targetPath, symlinkPath},
                    new String[0],listener.getLogger(), baseDir).join();
                if(r!=0)
                    listener.getLogger().println("ln failed: "+r);
            } catch (IOException e) {
                PrintStream log = listener.getLogger();
                log.println("ln failed");
                Util.displayIOException(e,listener);
                e.printStackTrace( log );
            }
        }
    }

729 730 731 732 733 734 735
    /**
     * 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
736 737 738 739
     * @deprecated This method is broken (see ISSUE#1666). It should probably
     * 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. 
740
     */
741
    @Deprecated
742 743 744 745 746 747 748 749 750
    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 已提交
751 752
    /**
     * Wraps with the error icon and the CSS class to render error message.
753
     * @since 1.173
K
kohsuke 已提交
754 755 756 757 758 759 760
     */
    public static String wrapToErrorSpan(String s) {
        s = "<span class=error><img src='"+
            Stapler.getCurrentRequest().getContextPath()+ Hudson.RESOURCE_PATH+
            "/images/none.gif' height=16 width=1>"+s+"</span>";
        return s;
    }
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
    
    /**
     * 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 已提交
780

K
kohsuke 已提交
781 782
    public static final SimpleDateFormat XS_DATETIME_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

783 784 785 786
    // Note: RFC822 dates must not be localized!
    public static final SimpleDateFormat RFC822_DATETIME_FORMATTER
            = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);

K
kohsuke 已提交
787 788 789 790 791 792 793 794
    static {
        XS_DATETIME_FORMATTER.setTimeZone(new SimpleTimeZone(0,"GMT"));
    }



    private static final Logger LOGGER = Logger.getLogger(Util.class.getName());
}