1 package hudson; 2 3 import hudson.model.TaskListener; 4 import hudson.util.IOException2; 5 import org.apache.tools.ant.BuildException; 6 import org.apache.tools.ant.taskdefs.Chmod; 7 import org.apache.tools.ant.taskdefs.Copy; 8 9 import java.io.BufferedReader ; 10 import java.io.ByteArrayOutputStream ; 11 import java.io.File ; 12 import java.io.FileOutputStream ; 13 import java.io.FileReader ; 14 import java.io.IOException ; 15 import java.io.InputStream ; 16 import java.io.OutputStream ; 17 import java.io.OutputStreamWriter ; 18 import java.net.InetAddress ; 19 import java.net.UnknownHostException ; 20 import java.security.DigestInputStream ; 21 import java.security.MessageDigest ; 22 import java.security.NoSuchAlgorithmException ; 23 import java.text.SimpleDateFormat ; 24 import java.util.ArrayList ; 25 import java.util.Collection ; 26 import java.util.List ; 27 import java.util.Locale ; 28 import java.util.Map ; 29 import java.util.ResourceBundle ; 30 import java.util.SimpleTimeZone ; 31 import java.util.StringTokenizer ; 32 import java.util.logging.Level ; 33 import java.util.logging.Logger ; 34 import java.util.regex.Matcher ; 35 import java.util.regex.Pattern ; 36 37 40 public class Util { 41 42 45 public static <T> List <T> filter( List <?> base, Class <T> type ) { 46 List <T> r = new ArrayList <T>(); 47 for (Object i : base) { 48 if(type.isInstance(i)) 49 r.add(type.cast(i)); 50 } 51 return r; 52 } 53 54 61 public static String replaceMacro(String s, Map <String ,String > properties) { 62 int idx=0; 63 while((idx=s.indexOf('$',idx))>=0) { 64 int end=idx+1; 66 while(end<s.length()) { 67 char ch = s.charAt(end); 68 if(!Character.isJavaIdentifierPart(ch)) 69 break; 70 else 71 end++; 72 } 73 String key = s.substring(idx+1,end); 74 String value = properties.get(key); 75 if(value==null) { 76 idx++; } else { 78 s = s.substring(0,idx)+value+s.substring(end); 79 } 80 } 81 82 return s; 83 } 84 85 88 public static String loadFile(File logfile) throws IOException { 89 if(!logfile.exists()) 90 return ""; 91 92 StringBuffer str = new StringBuffer ((int)logfile.length()); 93 94 BufferedReader r = new BufferedReader (new FileReader (logfile)); 95 char[] buf = new char[1024]; 96 int len; 97 while((len=r.read(buf,0,buf.length))>0) 98 str.append(buf,0,len); 99 r.close(); 100 101 return str.toString(); 102 } 103 104 111 public static void deleteContentsRecursive(File file) throws IOException { 112 File [] files = file.listFiles(); 113 if(files==null) 114 return; for (File child : files) { 116 if (child.isDirectory()) 117 deleteContentsRecursive(child); 118 deleteFile(child); 119 } 120 } 121 122 private static void deleteFile(File f) throws IOException { 123 if (!f.delete()) { 124 if(!f.exists()) 125 return; 127 128 try { 131 Chmod chmod = new Chmod(); 132 chmod.setProject(new org.apache.tools.ant.Project()); 133 chmod.setFile(f); 134 chmod.setPerm("u+w"); 135 chmod.execute(); 136 } catch (BuildException e) { 137 LOGGER.log(Level.INFO,"Failed to chmod "+f,e); 138 } 139 140 throw new IOException ("Unable to delete " + f.getPath()); 141 142 } 143 } 144 145 public static void deleteRecursive(File dir) throws IOException { 146 deleteContentsRecursive(dir); 147 deleteFile(dir); 148 } 149 150 153 public static File createTempDir() throws IOException { 154 File tmp = File.createTempFile("hudson", "tmp"); 155 if(!tmp.delete()) 156 throw new IOException ("Failed to delete "+tmp); 157 if(!tmp.mkdirs()) 158 throw new IOException ("Failed to create a new directory "+tmp); 159 return tmp; 160 } 161 162 private static final Pattern errorCodeParser = Pattern.compile(".*CreateProcess.*error=([0-9]+).*"); 163 164 168 public static void displayIOException( IOException e, TaskListener listener ) { 169 String msg = getWin32ErrorMessage(e); 170 if(msg!=null) 171 listener.getLogger().println(msg); 172 } 173 174 180 public static String getWin32ErrorMessage(IOException e) { 181 String msg = e.getMessage(); 182 if(msg==null) 183 return null; Matcher m = errorCodeParser.matcher(msg); 185 if(!m.matches()) 186 return null; 188 try { 189 ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors"); 190 return rb.getString("error"+m.group(1)); 191 } catch (Exception _) { 192 return null; 194 } 195 } 196 197 200 public static String getHostName() { 201 try { 202 return InetAddress.getLocalHost().getHostName(); 203 } catch (UnknownHostException e) { 204 return "localhost"; 205 } 206 } 207 208 public static void copyStream(InputStream in,OutputStream out) throws IOException { 209 byte[] buf = new byte[8192]; 210 int len; 211 while((len=in.read(buf))>0) 212 out.write(buf,0,len); 213 } 214 215 public static String [] tokenize(String s) { 216 StringTokenizer st = new StringTokenizer (s); 217 String [] a = new String [st.countTokens()]; 218 for (int i = 0; st.hasMoreTokens(); i++) 219 a[i] = st.nextToken(); 220 return a; 221 } 222 223 public static String [] mapToEnv(Map <String ,String > m) { 224 String [] r = new String [m.size()]; 225 int idx=0; 226 227 for (final Map.Entry <String ,String > e : m.entrySet()) { 228 r[idx++] = e.getKey() + '=' + e.getValue(); 229 } 230 return r; 231 } 232 233 public static int min(int x, int... values) { 234 for (int i : values) { 235 if(i<x) 236 x=i; 237 } 238 return x; 239 } 240 241 public static String nullify(String v) { 242 if(v!=null && v.length()==0) v=null; 243 return v; 244 } 245 246 249 private static final byte[] garbage = new byte[8192]; 250 251 257 public static String getDigestOf(InputStream source) throws IOException { 258 try { 259 MessageDigest md5 = MessageDigest.getInstance("MD5"); 260 261 DigestInputStream in =new DigestInputStream (source,md5); 262 try { 263 while(in.read(garbage)>0) 264 ; } finally { 266 in.close(); 267 } 268 return toHexString(md5.digest()); 269 } catch (NoSuchAlgorithmException e) { 270 throw new IOException2("MD5 not installed",e); } 272 } 273 274 public static String toHexString(byte[] data, int start, int len) { 275 StringBuffer buf = new StringBuffer (); 276 for( int i=0; i<len; i++ ) { 277 int b = data[start+i]&0xFF; 278 if(b<16) buf.append('0'); 279 buf.append(Integer.toHexString(b)); 280 } 281 return buf.toString(); 282 } 283 284 public static String toHexString(byte[] bytes) { 285 return toHexString(bytes,0,bytes.length); 286 } 287 288 public static String getTimeSpanString(long duration) { 289 duration /= 1000; 290 if(duration<60) 291 return combine(duration,"second"); 292 duration /= 60; 293 if(duration<60) 294 return combine(duration,"minute"); 295 duration /= 60; 296 if(duration<24) 297 return combine(duration,"hour"); 298 duration /= 24; 299 if(duration<30) 300 return combine(duration,"day"); 301 duration /= 30; 302 if(duration<12) 303 return combine(duration,"month"); 304 duration /= 12; 305 return combine(duration,"year"); 306 } 307 308 311 public static String combine(long n, String suffix) { 312 String s = Long.toString(n)+' '+suffix; 313 if(n!=1) 314 s += 's'; 315 return s; 316 } 317 318 321 public static <T> List <T> createSubList( Collection <?> source, Class <T> type ) { 322 List <T> r = new ArrayList <T>(); 323 for (Object item : source) { 324 if(type.isInstance(item)) 325 r.add(type.cast(item)); 326 } 327 return r; 328 } 329 330 333 public static String encode(String s) { 334 try { 335 boolean escaped = false; 336 337 StringBuffer out = new StringBuffer (s.length()); 338 339 ByteArrayOutputStream buf = new ByteArrayOutputStream (); 340 OutputStreamWriter w = new OutputStreamWriter (buf,"UTF-8"); 341 342 for (int i = 0; i < s.length(); i++) { 343 int c = (int) s.charAt(i); 344 if (c<128 && c!=' ') { 345 out.append((char) c); 346 } else { 347 w.write(c); 349 w.flush(); 350 for (byte b : buf.toByteArray()) { 351 out.append('%'); 352 out.append(toDigit((b >> 4) & 0xF)); 353 out.append(toDigit(b & 0xF)); 354 } 355 buf.reset(); 356 escaped = true; 357 } 358 } 359 360 return escaped ? out.toString() : s; 361 } catch (IOException e) { 362 throw new Error (e); } 364 } 365 366 369 public static String escape(String text) { 370 StringBuffer buf = new StringBuffer (text.length()+64); 371 for( int i=0; i<text.length(); i++ ) { 372 char ch = text.charAt(i); 373 if(ch=='\n') 374 buf.append("<br>"); 375 else 376 if(ch=='<') 377 buf.append("<"); 378 else 379 if(ch=='&') 380 buf.append("&"); 381 else 382 if(ch==' ') 383 buf.append(" "); 384 else 385 buf.append(ch); 386 } 387 return buf.toString(); 388 } 389 390 private static char toDigit(int n) { 391 char ch = Character.forDigit(n,16); 392 if(ch>='a') ch = (char)(ch-'a'+'A'); 393 return ch; 394 } 395 396 399 public static void touch(File file) throws IOException { 400 new FileOutputStream (file).close(); 401 } 402 403 406 public static void copyFile(File src, File dst) throws BuildException { 407 Copy cp = new Copy(); 408 cp.setProject(new org.apache.tools.ant.Project()); 409 cp.setTofile(dst); 410 cp.setFile(src); 411 cp.setOverwrite(true); 412 cp.execute(); 413 } 414 415 418 public static String fixNull(String s) { 419 if(s==null) return ""; 420 else return s; 421 } 422 423 426 public static String fixEmpty(String s) { 427 if(s==null || s.length()==0) return null; 428 return s; 429 } 430 431 434 public static String getFileName(String filePath) { 435 int idx = filePath.lastIndexOf('\\'); 436 if(idx>=0) 437 return getFileName(filePath.substring(idx+1)); 438 idx = filePath.lastIndexOf('/'); 439 if(idx>=0) 440 return getFileName(filePath.substring(idx+1)); 441 return filePath; 442 } 443 444 public static final SimpleDateFormat XS_DATETIME_FORMATTER = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss'Z'"); 445 446 public static final SimpleDateFormat RFC822_DATETIME_FORMATTER 448 = new SimpleDateFormat ("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US); 449 450 static { 451 XS_DATETIME_FORMATTER.setTimeZone(new SimpleTimeZone (0,"GMT")); 452 } 453 454 455 456 private static final Logger LOGGER = Logger.getLogger(Util.class.getName()); 457 458 } 459 | Popular Tags |