| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.build; |
| 7 |
|
| 8 |
import java.io.BufferedInputStream; |
| 9 |
import java.io.BufferedOutputStream; |
| 10 |
import java.io.BufferedReader; |
| 11 |
import java.io.ByteArrayOutputStream; |
| 12 |
import java.io.File; |
| 13 |
import java.io.FilterOutputStream; |
| 14 |
import java.io.IOException; |
| 15 |
import java.io.InputStream; |
| 16 |
import java.io.InputStreamReader; |
| 17 |
import java.io.OutputStream; |
| 18 |
import java.io.PrintStream; |
| 19 |
import java.lang.annotation.Documented; |
| 20 |
import java.lang.annotation.ElementType; |
| 21 |
import java.lang.annotation.Retention; |
| 22 |
import java.lang.annotation.RetentionPolicy; |
| 23 |
import java.lang.annotation.Target; |
| 24 |
import java.lang.reflect.Field; |
| 25 |
import java.lang.reflect.InvocationTargetException; |
| 26 |
import java.lang.reflect.Method; |
| 27 |
import java.lang.reflect.Modifier; |
| 28 |
import java.net.URL; |
| 29 |
import java.nio.charset.StandardCharsets; |
| 30 |
import java.nio.file.FileAlreadyExistsException; |
| 31 |
import java.nio.file.FileVisitResult; |
| 32 |
import java.nio.file.Files; |
| 33 |
import java.nio.file.Path; |
| 34 |
import java.nio.file.Paths; |
| 35 |
import java.nio.file.SimpleFileVisitor; |
| 36 |
import java.nio.file.attribute.BasicFileAttributes; |
| 37 |
import java.security.MessageDigest; |
| 38 |
import java.security.NoSuchAlgorithmException; |
| 39 |
import java.util.ArrayList; |
| 40 |
import java.util.Arrays; |
| 41 |
import java.util.Comparator; |
| 42 |
import java.util.List; |
| 43 |
import java.util.concurrent.TimeUnit; |
| 44 |
import java.util.jar.JarOutputStream; |
| 45 |
import java.util.zip.CRC32; |
| 46 |
import java.util.zip.Deflater; |
| 47 |
import java.util.zip.ZipEntry; |
| 48 |
import java.util.zip.ZipOutputStream; |
| 49 |
|
| 50 |
|
| 51 |
/** |
| 52 |
* This class is a complete pure Java build tool. It allows to build this |
| 53 |
* project without any external dependencies except a JDK. |
| 54 |
* Advantages: ability to debug the build, extensible, flexible, |
| 55 |
* no XML, a bit faster. |
| 56 |
*/ |
| 57 |
public class BuildBase { |
| 58 |
|
| 59 |
/** |
| 60 |
* Stores descriptions for methods which can be invoked as build targets. |
| 61 |
*/ |
| 62 |
@Retention(RetentionPolicy.RUNTIME) |
| 63 |
@Target(ElementType.METHOD) |
| 64 |
@Documented |
| 65 |
public static @interface Description { |
| 66 |
String summary() default ""; |
| 67 |
} |
| 68 |
|
| 69 |
/** |
| 70 |
* A list of strings. |
| 71 |
*/ |
| 72 |
public static class StringList extends ArrayList<String> { |
| 73 |
|
| 74 |
private static final long serialVersionUID = 1L; |
| 75 |
|
| 76 |
StringList(String... args) { |
| 77 |
super(); |
| 78 |
addAll(Arrays.asList(args)); |
| 79 |
} |
| 80 |
|
| 81 |
/** |
| 82 |
* Add a list of strings. |
| 83 |
* |
| 84 |
* @param args the list to add |
| 85 |
* @return the new list |
| 86 |
*/ |
| 87 |
public StringList plus(String...args) { |
| 88 |
StringList newList = new StringList(); |
| 89 |
newList.addAll(this); |
| 90 |
newList.addAll(Arrays.asList(args)); |
| 91 |
return newList; |
| 92 |
} |
| 93 |
|
| 94 |
/** |
| 95 |
* Convert this list to a string array. |
| 96 |
* |
| 97 |
* @return the string array |
| 98 |
*/ |
| 99 |
public String[] array() { |
| 100 |
String[] list = new String[size()]; |
| 101 |
for (int i = 0; i < size(); i++) { |
| 102 |
list[i] = get(i); |
| 103 |
} |
| 104 |
return list; |
| 105 |
} |
| 106 |
|
| 107 |
} |
| 108 |
|
| 109 |
/** |
| 110 |
* A list of files. |
| 111 |
*/ |
| 112 |
public static class FileList extends ArrayList<Path> { |
| 113 |
|
| 114 |
private static final long serialVersionUID = 1L; |
| 115 |
|
| 116 |
/** |
| 117 |
* Remove the files that match from the list. |
| 118 |
* Patterns must start or end with a *. |
| 119 |
* |
| 120 |
* @param pattern the pattern of the file names to remove |
| 121 |
* @return the new file list |
| 122 |
*/ |
| 123 |
public FileList exclude(String pattern) { |
| 124 |
return filter(false, pattern); |
| 125 |
} |
| 126 |
|
| 127 |
/** |
| 128 |
* Only keep the files that match. |
| 129 |
* Patterns must start or end with a *. |
| 130 |
* |
| 131 |
* @param pattern the pattern of the file names to keep |
| 132 |
* @return the new file list |
| 133 |
*/ |
| 134 |
public FileList keep(String pattern) { |
| 135 |
return filter(true, pattern); |
| 136 |
} |
| 137 |
|
| 138 |
/** |
| 139 |
* Filter a list of file names. |
| 140 |
* |
| 141 |
* @param keep if matching file names should be kept or removed |
| 142 |
* @param pattern the file name pattern |
| 143 |
* @return the filtered file list |
| 144 |
*/ |
| 145 |
private FileList filter(boolean keep, String pattern) { |
| 146 |
boolean start = false; |
| 147 |
if (pattern.endsWith("*")) { |
| 148 |
pattern = pattern.substring(0, pattern.length() - 1); |
| 149 |
start = true; |
| 150 |
} else if (pattern.startsWith("*")) { |
| 151 |
pattern = pattern.substring(1); |
| 152 |
} |
| 153 |
if (pattern.indexOf('*') >= 0) { |
| 154 |
throw new RuntimeException( |
| 155 |
"Unsupported pattern, may only start or end with *:" |
| 156 |
+ pattern); |
| 157 |
} |
| 158 |
// normalize / and \ |
| 159 |
pattern = BuildBase.replaceAll(pattern, "/", File.separator); |
| 160 |
FileList list = new FileList(); |
| 161 |
for (Path f : this) { |
| 162 |
String path = f.toString(); |
| 163 |
boolean match = start ? path.startsWith(pattern) : path.endsWith(pattern); |
| 164 |
if (match == keep) { |
| 165 |
list.add(f); |
| 166 |
} |
| 167 |
} |
| 168 |
return list; |
| 169 |
} |
| 170 |
|
| 171 |
} |
| 172 |
|
| 173 |
/** |
| 174 |
* The output stream (System.out). |
| 175 |
*/ |
| 176 |
protected final PrintStream sysOut = System.out; |
| 177 |
|
| 178 |
/** |
| 179 |
* If output should be disabled. |
| 180 |
*/ |
| 181 |
protected boolean quiet; |
| 182 |
|
| 183 |
/** |
| 184 |
* The full path to the executable of the current JRE. |
| 185 |
*/ |
| 186 |
protected final String javaExecutable = System.getProperty("java.home") + |
| 187 |
File.separator + "bin" + File.separator + "java"; |
| 188 |
|
| 189 |
/** |
| 190 |
* The full path to the tools jar of the current JDK. |
| 191 |
*/ |
| 192 |
protected final String javaToolsJar = System.getProperty("java.home") + File.separator + ".." + |
| 193 |
File.separator + "lib" + File.separator + "tools.jar"; |
| 194 |
|
| 195 |
/** |
| 196 |
* This method should be called by the main method. |
| 197 |
* |
| 198 |
* @param args the command line parameters |
| 199 |
*/ |
| 200 |
protected void run(String... args) { |
| 201 |
long time = System.nanoTime(); |
| 202 |
if (args.length == 0) { |
| 203 |
all(); |
| 204 |
} else { |
| 205 |
for (String a : args) { |
| 206 |
if ("-quiet".equals(a)) { |
| 207 |
quiet = true; |
| 208 |
} else if ("-".equals(a)) { |
| 209 |
runShell(); |
| 210 |
return; |
| 211 |
} else if (a.startsWith("-D")) { |
| 212 |
String value; |
| 213 |
String key = a.substring(2); |
| 214 |
int valueIndex = key.indexOf('='); |
| 215 |
if (valueIndex >= 0) { |
| 216 |
value = key.substring(valueIndex + 1); |
| 217 |
key = key.substring(0, valueIndex); |
| 218 |
} else { |
| 219 |
value = "true"; |
| 220 |
} |
| 221 |
System.setProperty(key, value); |
| 222 |
} else { |
| 223 |
if (!runTarget(a)) { |
| 224 |
break; |
| 225 |
} |
| 226 |
} |
| 227 |
} |
| 228 |
} |
| 229 |
println("Done in " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - time) + " ms"); |
| 230 |
} |
| 231 |
|
| 232 |
private boolean runTarget(String target) { |
| 233 |
Method m = null; |
| 234 |
try { |
| 235 |
m = getClass().getMethod(target); |
| 236 |
} catch (Exception e) { |
| 237 |
sysOut.println("Unknown target: " + target); |
| 238 |
projectHelp(); |
| 239 |
return false; |
| 240 |
} |
| 241 |
println("Target: " + target); |
| 242 |
invoke(m, this, new Object[0]); |
| 243 |
return true; |
| 244 |
} |
| 245 |
|
| 246 |
private void runShell() { |
| 247 |
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); |
| 248 |
String last = "", line; |
| 249 |
System.out.println("Shell mode. Type the target, then [Enter]. " + |
| 250 |
"Just [Enter] repeats the last target."); |
| 251 |
while (true) { |
| 252 |
System.out.print("build> "); |
| 253 |
try { |
| 254 |
line = reader.readLine(); |
| 255 |
} catch (IOException e) { |
| 256 |
throw new RuntimeException(e); |
| 257 |
} |
| 258 |
if (line == null || line.equals("exit") || line.equals("quit")) { |
| 259 |
break; |
| 260 |
} else if (line.length() == 0) { |
| 261 |
line = last; |
| 262 |
} |
| 263 |
long time = System.nanoTime(); |
| 264 |
try { |
| 265 |
runTarget(line); |
| 266 |
} catch (Exception e) { |
| 267 |
System.out.println(e); |
| 268 |
} |
| 269 |
println("Done in " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - time) + " ms"); |
| 270 |
last = line; |
| 271 |
} |
| 272 |
} |
| 273 |
|
| 274 |
private static Object invoke(Method m, Object instance, Object[] args) { |
| 275 |
try { |
| 276 |
try { |
| 277 |
return m.invoke(instance, args); |
| 278 |
} catch (InvocationTargetException e) { |
| 279 |
throw e.getCause(); |
| 280 |
} |
| 281 |
} catch (Error | RuntimeException e) { |
| 282 |
throw e; |
| 283 |
} catch (Throwable e) { |
| 284 |
throw new RuntimeException(e); |
| 285 |
} |
| 286 |
} |
| 287 |
|
| 288 |
/** |
| 289 |
* This method is called if no other target is specified in the command |
| 290 |
* line. The default behavior is to call projectHelp(). Override this method |
| 291 |
* if you want another default behavior. |
| 292 |
*/ |
| 293 |
protected void all() { |
| 294 |
projectHelp(); |
| 295 |
} |
| 296 |
|
| 297 |
/** |
| 298 |
* Emit a beep. |
| 299 |
*/ |
| 300 |
protected void beep() { |
| 301 |
sysOut.print("\007"); |
| 302 |
sysOut.flush(); |
| 303 |
} |
| 304 |
|
| 305 |
/** |
| 306 |
* Lists all targets (all public methods non-static methods without |
| 307 |
* parameters). |
| 308 |
*/ |
| 309 |
protected void projectHelp() { |
| 310 |
Method[] methods = getClass().getDeclaredMethods(); |
| 311 |
Arrays.sort(methods, Comparator.comparing(Method::getName)); |
| 312 |
sysOut.println("Targets:"); |
| 313 |
String description; |
| 314 |
for (Method m : methods) { |
| 315 |
int mod = m.getModifiers(); |
| 316 |
if (!Modifier.isStatic(mod) && Modifier.isPublic(mod) |
| 317 |
&& m.getParameterTypes().length == 0) { |
| 318 |
if (m.isAnnotationPresent(Description.class)) { |
| 319 |
description = String.format("%1$-20s %2$s", |
| 320 |
m.getName(), m.getAnnotation(Description.class).summary()); |
| 321 |
} else { |
| 322 |
description = m.getName(); |
| 323 |
} |
| 324 |
sysOut.println(description); |
| 325 |
} |
| 326 |
} |
| 327 |
sysOut.println(); |
| 328 |
} |
| 329 |
|
| 330 |
protected static boolean isWindows() { |
| 331 |
return System.getProperty("os.name").toLowerCase().contains("windows"); |
| 332 |
} |
| 333 |
|
| 334 |
/** |
| 335 |
* Execute a script in a separate process. |
| 336 |
* In Windows, the batch file with this name (.bat) is run. |
| 337 |
* |
| 338 |
* @param script the program to run |
| 339 |
* @param args the command line parameters |
| 340 |
* @return the exit value |
| 341 |
*/ |
| 342 |
protected int execScript(String script, StringList args) { |
| 343 |
if (isWindows()) { |
| 344 |
// Under windows, we use the "cmd" command interpreter since it will |
| 345 |
// search the path for us without us having to hard-code an |
| 346 |
// extension for the script we want. (Sometimes we don't know if the |
| 347 |
// extension will be .bat or .cmd) |
| 348 |
StringList newArgs = new StringList(); |
| 349 |
newArgs.add("/C"); |
| 350 |
newArgs.add(script); |
| 351 |
newArgs.addAll(args); |
| 352 |
return exec("cmd", newArgs); |
| 353 |
} |
| 354 |
return exec(script, args); |
| 355 |
} |
| 356 |
|
| 357 |
/** |
| 358 |
* Execute java in a separate process, but using the java executable of the |
| 359 |
* current JRE. |
| 360 |
* |
| 361 |
* @param args the command line parameters for the java command |
| 362 |
* @return the exit value |
| 363 |
*/ |
| 364 |
protected int execJava(StringList args) { |
| 365 |
return exec(javaExecutable, args); |
| 366 |
} |
| 367 |
|
| 368 |
/** |
| 369 |
* Execute a program in a separate process. |
| 370 |
* |
| 371 |
* @param command the program to run |
| 372 |
* @param args the command line parameters |
| 373 |
* @return the exit value |
| 374 |
*/ |
| 375 |
protected int exec(String command, StringList args) { |
| 376 |
try { |
| 377 |
print(command); |
| 378 |
StringList cmd = new StringList(); |
| 379 |
cmd = cmd.plus(command); |
| 380 |
if (args != null) { |
| 381 |
for (String a : args) { |
| 382 |
print(" " + a); |
| 383 |
} |
| 384 |
cmd.addAll(args); |
| 385 |
} |
| 386 |
println(""); |
| 387 |
ProcessBuilder pb = new ProcessBuilder(); |
| 388 |
pb.command(cmd.array()); |
| 389 |
pb.redirectErrorStream(true); |
| 390 |
Process p = pb.start(); |
| 391 |
copyInThread(p.getInputStream(), quiet ? null : sysOut); |
| 392 |
p.waitFor(); |
| 393 |
return p.exitValue(); |
| 394 |
} catch (Exception e) { |
| 395 |
throw new RuntimeException(e); |
| 396 |
} |
| 397 |
} |
| 398 |
|
| 399 |
private static void copyInThread(final InputStream in, final OutputStream out) { |
| 400 |
new Thread() { |
| 401 |
@Override |
| 402 |
public void run() { |
| 403 |
try { |
| 404 |
while (true) { |
| 405 |
int x = in.read(); |
| 406 |
if (x < 0) { |
| 407 |
return; |
| 408 |
} |
| 409 |
if (out != null) { |
| 410 |
out.write(x); |
| 411 |
} |
| 412 |
} |
| 413 |
} catch (Exception e) { |
| 414 |
throw new RuntimeException(e); |
| 415 |
} |
| 416 |
} |
| 417 |
}.start(); |
| 418 |
} |
| 419 |
|
| 420 |
/** |
| 421 |
* Read a final static field in a class using reflection. |
| 422 |
* |
| 423 |
* @param className the name of the class |
| 424 |
* @param fieldName the field name |
| 425 |
* @return the value as a string |
| 426 |
*/ |
| 427 |
protected static String getStaticField(String className, String fieldName) { |
| 428 |
try { |
| 429 |
Class<?> clazz = Class.forName(className); |
| 430 |
Field field = clazz.getField(fieldName); |
| 431 |
return field.get(null).toString(); |
| 432 |
} catch (Exception e) { |
| 433 |
throw new RuntimeException("Can not read field " + className + "." |
| 434 |
+ fieldName, e); |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
/** |
| 439 |
* Copy files to the specified target directory. |
| 440 |
* |
| 441 |
* @param targetDir the target directory |
| 442 |
* @param files the list of files to copy |
| 443 |
* @param baseDir the base directory |
| 444 |
*/ |
| 445 |
protected void copy(String targetDir, FileList files, String baseDir) { |
| 446 |
Path target = Paths.get(targetDir); |
| 447 |
Path base = Paths.get(baseDir); |
| 448 |
println("Copying " + files.size() + " files to " + target); |
| 449 |
for (Path f : files) { |
| 450 |
Path t = target.resolve(base.relativize(f)); |
| 451 |
byte[] data = readFile(f); |
| 452 |
mkdirs(t.getParent()); |
| 453 |
writeFile(t, data); |
| 454 |
} |
| 455 |
} |
| 456 |
|
| 457 |
private static PrintStream filter(PrintStream out, final String[] exclude) { |
| 458 |
return new PrintStream(new FilterOutputStream(out) { |
| 459 |
private ByteArrayOutputStream buff = new ByteArrayOutputStream(); |
| 460 |
|
| 461 |
@Override |
| 462 |
public void write(byte[] b) throws IOException { |
| 463 |
write(b, 0, b.length); |
| 464 |
} |
| 465 |
|
| 466 |
@Override |
| 467 |
public void write(byte[] b, int off, int len) throws IOException { |
| 468 |
for (int i = off; i < len; i++) { |
| 469 |
write(b[i]); |
| 470 |
} |
| 471 |
} |
| 472 |
|
| 473 |
public void write(byte b) throws IOException { |
| 474 |
buff.write(b); |
| 475 |
if (b == '\n') { |
| 476 |
byte[] data = buff.toByteArray(); |
| 477 |
String line = new String(data, StandardCharsets.UTF_8); |
| 478 |
boolean print = true; |
| 479 |
for (String l : exclude) { |
| 480 |
if (line.startsWith(l)) { |
| 481 |
print = false; |
| 482 |
break; |
| 483 |
} |
| 484 |
} |
| 485 |
if (print) { |
| 486 |
out.write(data); |
| 487 |
} |
| 488 |
buff.reset(); |
| 489 |
} |
| 490 |
} |
| 491 |
|
| 492 |
@Override |
| 493 |
public void close() throws IOException { |
| 494 |
write('\n'); |
| 495 |
} |
| 496 |
}); |
| 497 |
} |
| 498 |
|
| 499 |
/** |
| 500 |
* Run a Javadoc task. |
| 501 |
* |
| 502 |
* @param args the command line arguments to pass |
| 503 |
*/ |
| 504 |
protected void javadoc(String...args) { |
| 505 |
int result; |
| 506 |
PrintStream old = System.out; |
| 507 |
try { |
| 508 |
println("Javadoc"); |
| 509 |
if (quiet) { |
| 510 |
System.setOut(filter(System.out, new String[] { |
| 511 |
"Loading source files for package", |
| 512 |
"Constructing Javadoc information...", |
| 513 |
"Generating ", |
| 514 |
"Standard Doclet", |
| 515 |
"Building tree for all the packages and classes...", |
| 516 |
"Building index for all the packages and classes...", |
| 517 |
"Building index for all classes..." |
| 518 |
})); |
| 519 |
} else { |
| 520 |
System.setOut(filter(System.out, new String[] { |
| 521 |
"Loading source files for package ", |
| 522 |
"Generating ", |
| 523 |
})); |
| 524 |
} |
| 525 |
Class<?> clazz; |
| 526 |
try { |
| 527 |
clazz = Class.forName("jdk.javadoc.internal.tool.Main"); |
| 528 |
} catch (Exception e) { |
| 529 |
clazz = Class.forName("com.sun.tools.javadoc.Main"); |
| 530 |
} |
| 531 |
Method execute = clazz.getMethod("execute", String[].class); |
| 532 |
result = (Integer) invoke(execute, null, new Object[] { args }); |
| 533 |
} catch (Exception e) { |
| 534 |
result = exec("javadoc", args(args)); |
| 535 |
} finally { |
| 536 |
System.setOut(old); |
| 537 |
} |
| 538 |
if (result != 0) { |
| 539 |
throw new RuntimeException("An error occurred, result=" + result); |
| 540 |
} |
| 541 |
} |
| 542 |
|
| 543 |
private static String convertBytesToString(byte[] value) { |
| 544 |
StringBuilder buff = new StringBuilder(value.length * 2); |
| 545 |
for (byte c : value) { |
| 546 |
int x = c & 0xff; |
| 547 |
buff.append(Integer.toString(x >> 4, 16)). |
| 548 |
append(Integer.toString(x & 0xf, 16)); |
| 549 |
} |
| 550 |
return buff.toString(); |
| 551 |
} |
| 552 |
|
| 553 |
/** |
| 554 |
* Generate the SHA1 checksum of a byte array. |
| 555 |
* |
| 556 |
* @param data the byte array |
| 557 |
* @return the SHA1 checksum |
| 558 |
*/ |
| 559 |
protected static String getSHA1(byte[] data) { |
| 560 |
MessageDigest md; |
| 561 |
try { |
| 562 |
md = MessageDigest.getInstance("SHA-1"); |
| 563 |
return convertBytesToString(md.digest(data)); |
| 564 |
} catch (NoSuchAlgorithmException e) { |
| 565 |
throw new RuntimeException(e); |
| 566 |
} |
| 567 |
} |
| 568 |
|
| 569 |
/** |
| 570 |
* Download a file if it does not yet exist. Maven is used if installed, so |
| 571 |
* that the file is first downloaded to the local repository and then copied |
| 572 |
* from there. |
| 573 |
* |
| 574 |
* @param target the target file name |
| 575 |
* @param group the Maven group id |
| 576 |
* @param artifact the Maven artifact id |
| 577 |
* @param version the Maven version id |
| 578 |
* @param sha1Checksum the SHA-1 checksum or null |
| 579 |
*/ |
| 580 |
protected void downloadUsingMaven(String target, String group, |
| 581 |
String artifact, String version, String sha1Checksum) { |
| 582 |
String repoDir = "https://repo1.maven.org/maven2"; |
| 583 |
Path targetFile = Paths.get(target); |
| 584 |
if (Files.exists(targetFile)) { |
| 585 |
return; |
| 586 |
} |
| 587 |
String repoFile = group.replace('.', '/') + "/" + artifact + "/" + version + "/" |
| 588 |
+ artifact + "-" + version + ".jar"; |
| 589 |
mkdirs(targetFile.toAbsolutePath().getParent()); |
| 590 |
Path localMavenDir = Paths.get(getLocalMavenDir()); |
| 591 |
if (Files.isDirectory(localMavenDir)) { |
| 592 |
Path f = localMavenDir.resolve(repoFile); |
| 593 |
if (!Files.exists(f)) { |
| 594 |
try { |
| 595 |
execScript("mvn", args( |
| 596 |
"org.apache.maven.plugins:maven-dependency-plugin:2.1:get", |
| 597 |
"-D" + "repoUrl=" + repoDir, |
| 598 |
"-D" + "artifact="+ group +":"+ artifact +":" + version)); |
| 599 |
} catch (RuntimeException e) { |
| 600 |
println("Could not download using Maven: " + e.toString()); |
| 601 |
} |
| 602 |
} |
| 603 |
if (Files.exists(f)) { |
| 604 |
byte[] data = readFile(f); |
| 605 |
String got = getSHA1(data); |
| 606 |
if (sha1Checksum == null) { |
| 607 |
println("SHA1 checksum: " + got); |
| 608 |
} else { |
| 609 |
if (!got.equals(sha1Checksum)) { |
| 610 |
throw new RuntimeException( |
| 611 |
"SHA1 checksum mismatch; got: " + got + |
| 612 |
" expected: " + sha1Checksum + |
| 613 |
" for file " + f.toAbsolutePath()); |
| 614 |
} |
| 615 |
} |
| 616 |
writeFile(targetFile, data); |
| 617 |
return; |
| 618 |
} |
| 619 |
} |
| 620 |
String fileURL = repoDir + "/" + repoFile; |
| 621 |
download(target, fileURL, sha1Checksum); |
| 622 |
} |
| 623 |
|
| 624 |
protected String getLocalMavenDir() { |
| 625 |
return System.getProperty("user.home") + "/.m2/repository"; |
| 626 |
} |
| 627 |
|
| 628 |
/** |
| 629 |
* Download a file if it does not yet exist. |
| 630 |
* If no checksum is used (that is, if the parameter is null), the |
| 631 |
* checksum is printed. For security, checksums should always be used. |
| 632 |
* |
| 633 |
* @param target the target file name |
| 634 |
* @param fileURL the source url of the file |
| 635 |
* @param sha1Checksum the SHA-1 checksum or null |
| 636 |
*/ |
| 637 |
protected void download(String target, String fileURL, String sha1Checksum) { |
| 638 |
Path targetFile = Paths.get(target); |
| 639 |
if (Files.exists(targetFile)) { |
| 640 |
return; |
| 641 |
} |
| 642 |
mkdirs(targetFile.toAbsolutePath().getParent()); |
| 643 |
ByteArrayOutputStream buff = new ByteArrayOutputStream(); |
| 644 |
try { |
| 645 |
println("Downloading " + fileURL); |
| 646 |
URL url = new URL(fileURL); |
| 647 |
InputStream in = new BufferedInputStream(url.openStream()); |
| 648 |
long last = System.nanoTime(); |
| 649 |
int len = 0; |
| 650 |
while (true) { |
| 651 |
long now = System.nanoTime(); |
| 652 |
if (now - last > 1_000_000_000L) { |
| 653 |
println("Downloaded " + len + " bytes"); |
| 654 |
last = now; |
| 655 |
} |
| 656 |
int x = in.read(); |
| 657 |
len++; |
| 658 |
if (x < 0) { |
| 659 |
break; |
| 660 |
} |
| 661 |
buff.write(x); |
| 662 |
} |
| 663 |
in.close(); |
| 664 |
} catch (IOException e) { |
| 665 |
throw new RuntimeException("Error downloading " + fileURL + " to " + target, e); |
| 666 |
} |
| 667 |
byte[] data = buff.toByteArray(); |
| 668 |
String got = getSHA1(data); |
| 669 |
if (sha1Checksum == null) { |
| 670 |
println("SHA1 checksum: " + got); |
| 671 |
} else { |
| 672 |
if (!got.equals(sha1Checksum)) { |
| 673 |
throw new RuntimeException("SHA1 checksum mismatch; got: " + |
| 674 |
got + " expected: " + sha1Checksum + " for file " + target); |
| 675 |
|
| 676 |
} |
| 677 |
} |
| 678 |
writeFile(targetFile, data); |
| 679 |
} |
| 680 |
|
| 681 |
/** |
| 682 |
* Get the list of files in the given directory and all subdirectories. |
| 683 |
* |
| 684 |
* @param dir the source directory |
| 685 |
* @return the file list |
| 686 |
*/ |
| 687 |
protected FileList files(String dir) { |
| 688 |
FileList list = new FileList(); |
| 689 |
addFiles(list, Paths.get(dir)); |
| 690 |
return list; |
| 691 |
} |
| 692 |
|
| 693 |
/** |
| 694 |
* Create a string list. |
| 695 |
* |
| 696 |
* @param args the arguments |
| 697 |
* @return the string list |
| 698 |
*/ |
| 699 |
protected static StringList args(String...args) { |
| 700 |
return new StringList(args); |
| 701 |
} |
| 702 |
|
| 703 |
private static void addFiles(FileList list, Path file) { |
| 704 |
if (file.getFileName().toString().startsWith(".svn")) { |
| 705 |
// ignore |
| 706 |
} else if (Files.isDirectory(file)) { |
| 707 |
try { |
| 708 |
Files.walkFileTree(file, new SimpleFileVisitor<Path>() { |
| 709 |
@Override |
| 710 |
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { |
| 711 |
list.add(file); |
| 712 |
return FileVisitResult.CONTINUE; |
| 713 |
} |
| 714 |
}); |
| 715 |
} catch (IOException e) { |
| 716 |
throw new RuntimeException("Error reading directory " + file, e); |
| 717 |
} |
| 718 |
} else { |
| 719 |
list.add(file); |
| 720 |
} |
| 721 |
} |
| 722 |
|
| 723 |
/** |
| 724 |
* Create or overwrite a file. |
| 725 |
* |
| 726 |
* @param file the file |
| 727 |
* @param data the data to write |
| 728 |
*/ |
| 729 |
public static void writeFile(Path file, byte[] data) { |
| 730 |
try { |
| 731 |
Files.write(file, data); |
| 732 |
} catch (IOException e) { |
| 733 |
throw new RuntimeException("Error writing to file " + file, e); |
| 734 |
} |
| 735 |
} |
| 736 |
|
| 737 |
/** |
| 738 |
* Read a file. The maximum file size is Integer.MAX_VALUE. |
| 739 |
* |
| 740 |
* @param file the file |
| 741 |
* @return the data |
| 742 |
*/ |
| 743 |
public static byte[] readFile(Path file) { |
| 744 |
try { |
| 745 |
return Files.readAllBytes(file); |
| 746 |
} catch (IOException e) { |
| 747 |
throw new RuntimeException("Error reading from file " + file, e); |
| 748 |
} |
| 749 |
} |
| 750 |
|
| 751 |
/** |
| 752 |
* Get the file name suffix. |
| 753 |
* |
| 754 |
* @param fileName the file name |
| 755 |
* @return the suffix or an empty string if there is none |
| 756 |
*/ |
| 757 |
static String getSuffix(String fileName) { |
| 758 |
int idx = fileName.lastIndexOf('.'); |
| 759 |
return idx < 0 ? "" : fileName.substring(idx); |
| 760 |
} |
| 761 |
|
| 762 |
/** |
| 763 |
* Create a jar file. |
| 764 |
* |
| 765 |
* @param destFile the target file name |
| 766 |
* @param files the file list |
| 767 |
* @param basePath the base path |
| 768 |
* @return the size of the jar file in KB |
| 769 |
*/ |
| 770 |
protected long jar(String destFile, FileList files, String basePath) { |
| 771 |
long kb = zipOrJar(destFile, files, basePath, false, false, true); |
| 772 |
println("Jar " + destFile + " (" + kb + " KB)"); |
| 773 |
return kb; |
| 774 |
} |
| 775 |
|
| 776 |
/** |
| 777 |
* Create a zip file. |
| 778 |
* |
| 779 |
* @param destFile the target file name |
| 780 |
* @param files the file list |
| 781 |
* @param basePath the base path |
| 782 |
* @param storeOnly if the files should not be compressed |
| 783 |
* @param sortBySuffix if the file should be sorted by the file suffix |
| 784 |
*/ |
| 785 |
protected void zip(String destFile, FileList files, String basePath, |
| 786 |
boolean storeOnly, boolean sortBySuffix) { |
| 787 |
long kb = zipOrJar(destFile, files, basePath, storeOnly, sortBySuffix, false); |
| 788 |
println("Zip " + destFile + " (" + kb + " KB)"); |
| 789 |
} |
| 790 |
|
| 791 |
private static long zipOrJar(String destFile, FileList files, |
| 792 |
String basePath, boolean storeOnly, boolean sortBySuffix, boolean jar) { |
| 793 |
if (sortBySuffix) { |
| 794 |
// for better compressibility, sort by suffix, then name |
| 795 |
files.sort((f1, f2) -> { |
| 796 |
String p1 = f1.toString(); |
| 797 |
String p2 = f2.toString(); |
| 798 |
int comp = getSuffix(p1).compareTo(getSuffix(p2)); |
| 799 |
if (comp == 0) { |
| 800 |
comp = p1.compareTo(p2); |
| 801 |
} |
| 802 |
return comp; |
| 803 |
}); |
| 804 |
} else if (jar) { |
| 805 |
files.sort(new Comparator<Path>() { |
| 806 |
private int priority(String path) { |
| 807 |
if (path.startsWith("META-INF/")) { |
| 808 |
if (path.equals("META-INF/MANIFEST.MF")) { |
| 809 |
return 0; |
| 810 |
} |
| 811 |
if (path.startsWith("services/", 9)) { |
| 812 |
return 1; |
| 813 |
} |
| 814 |
return 2; |
| 815 |
} |
| 816 |
if (!path.endsWith(".zip")) { |
| 817 |
return 3; |
| 818 |
} |
| 819 |
return 4; |
| 820 |
} |
| 821 |
|
| 822 |
@Override |
| 823 |
public int compare(Path f1, Path f2) { |
| 824 |
String p1 = f1.toString(); |
| 825 |
String p2 = f2.toString(); |
| 826 |
int comp = Integer.compare(priority(p1), priority(p2)); |
| 827 |
if (comp != 0) { |
| 828 |
return comp; |
| 829 |
} |
| 830 |
return p1.compareTo(p2); |
| 831 |
} |
| 832 |
}); |
| 833 |
} |
| 834 |
Path dest = Paths.get(destFile).toAbsolutePath(); |
| 835 |
mkdirs(dest.getParent()); |
| 836 |
Path base = Paths.get(basePath); |
| 837 |
try { |
| 838 |
if (Files.isDirectory(dest)) { |
| 839 |
throw new IOException( |
| 840 |
"Can't create the file as a directory with this name already exists: " |
| 841 |
+ destFile); |
| 842 |
} |
| 843 |
OutputStream out = new BufferedOutputStream(Files.newOutputStream(dest)); |
| 844 |
ZipOutputStream zipOut; |
| 845 |
if (jar) { |
| 846 |
zipOut = new JarOutputStream(out); |
| 847 |
} else { |
| 848 |
zipOut = new ZipOutputStream(out); |
| 849 |
} |
| 850 |
if (storeOnly) { |
| 851 |
zipOut.setMethod(ZipOutputStream.STORED); |
| 852 |
} |
| 853 |
zipOut.setLevel(Deflater.BEST_COMPRESSION); |
| 854 |
for (Path file : files) { |
| 855 |
String entryName = base.relativize(file).toString().replace('\\', '/'); |
| 856 |
byte[] data = readFile(file); |
| 857 |
ZipEntry entry = new ZipEntry(entryName); |
| 858 |
CRC32 crc = new CRC32(); |
| 859 |
crc.update(data); |
| 860 |
entry.setSize(data.length); |
| 861 |
entry.setCrc(crc.getValue()); |
| 862 |
zipOut.putNextEntry(entry); |
| 863 |
zipOut.write(data); |
| 864 |
zipOut.closeEntry(); |
| 865 |
} |
| 866 |
zipOut.closeEntry(); |
| 867 |
zipOut.close(); |
| 868 |
return Files.size(dest) / 1024; |
| 869 |
} catch (IOException e) { |
| 870 |
throw new RuntimeException("Error creating file " + destFile, e); |
| 871 |
} |
| 872 |
} |
| 873 |
|
| 874 |
/** |
| 875 |
* Get the current java specification version (for example, 1.8). |
| 876 |
* |
| 877 |
* @return the java specification version |
| 878 |
*/ |
| 879 |
protected static String getJavaSpecVersion() { |
| 880 |
return System.getProperty("java.specification.version"); |
| 881 |
} |
| 882 |
|
| 883 |
/** |
| 884 |
* Get the current Java version as integer value. |
| 885 |
* |
| 886 |
* @return the Java version (8, 9, 10, 11, 12, 13, etc) |
| 887 |
*/ |
| 888 |
public static int getJavaVersion() { |
| 889 |
int version = 8; |
| 890 |
String v = getJavaSpecVersion(); |
| 891 |
if (v != null) { |
| 892 |
int idx = v.indexOf('.'); |
| 893 |
if (idx >= 0) { |
| 894 |
// 1.8 |
| 895 |
v = v.substring(idx + 1); |
| 896 |
} |
| 897 |
version = Integer.parseInt(v); |
| 898 |
} |
| 899 |
return version; |
| 900 |
} |
| 901 |
|
| 902 |
private static List<String> getPaths(FileList files) { |
| 903 |
StringList list = new StringList(); |
| 904 |
for (Path f : files) { |
| 905 |
list.add(f.toString()); |
| 906 |
} |
| 907 |
return list; |
| 908 |
} |
| 909 |
|
| 910 |
/** |
| 911 |
* Compile the files. |
| 912 |
* |
| 913 |
* @param args the command line parameters |
| 914 |
* @param files the file list |
| 915 |
*/ |
| 916 |
protected void javac(StringList args, FileList files) { |
| 917 |
println("Compiling " + files.size() + " classes"); |
| 918 |
StringList params = new StringList(); |
| 919 |
params.addAll(args); |
| 920 |
params.addAll(getPaths(files.keep(".java"))); |
| 921 |
String[] array = params.array(); |
| 922 |
int result; |
| 923 |
PrintStream old = System.err; |
| 924 |
try { |
| 925 |
Class<?> clazz = Class.forName("com.sun.tools.javac.Main"); |
| 926 |
if (quiet) { |
| 927 |
System.setErr(filter(System.err, new String[] { |
| 928 |
"Note:" |
| 929 |
})); |
| 930 |
} |
| 931 |
Method compile = clazz.getMethod("compile", new Class<?>[] { String[].class }); |
| 932 |
Object instance = clazz.getDeclaredConstructor().newInstance(); |
| 933 |
result = (Integer) invoke(compile, instance, new Object[] { array }); |
| 934 |
} catch (Exception e) { |
| 935 |
e.printStackTrace(); |
| 936 |
result = exec("javac", new StringList(array)); |
| 937 |
} finally { |
| 938 |
System.setErr(old); |
| 939 |
} |
| 940 |
if (result != 0) { |
| 941 |
throw new RuntimeException("An error occurred"); |
| 942 |
} |
| 943 |
} |
| 944 |
|
| 945 |
/** |
| 946 |
* Call the main method of the given Java class using reflection. |
| 947 |
* |
| 948 |
* @param className the class name |
| 949 |
* @param args the command line parameters to pass |
| 950 |
*/ |
| 951 |
protected void java(String className, StringList args) { |
| 952 |
println("Running " + className); |
| 953 |
String[] array = args == null ? new String[0] : args.array(); |
| 954 |
try { |
| 955 |
Method main = Class.forName(className).getMethod("main", String[].class); |
| 956 |
invoke(main, null, new Object[] { array }); |
| 957 |
} catch (Exception e) { |
| 958 |
throw new RuntimeException(e); |
| 959 |
} |
| 960 |
} |
| 961 |
|
| 962 |
/** |
| 963 |
* Create the directory including the parent directories if they don't |
| 964 |
* exist. |
| 965 |
* |
| 966 |
* @param dir the directory to create |
| 967 |
*/ |
| 968 |
protected static void mkdir(String dir) { |
| 969 |
mkdirs(Paths.get(dir)); |
| 970 |
} |
| 971 |
|
| 972 |
private static void mkdirs(Path f) { |
| 973 |
try { |
| 974 |
Files.createDirectories(f); |
| 975 |
} catch (FileAlreadyExistsException e) { |
| 976 |
throw new RuntimeException("Can not create directory " + e.getFile() |
| 977 |
+ " because a file with this name exists"); |
| 978 |
} catch (IOException e) { |
| 979 |
throw new RuntimeException("Can not create directory " + f.toAbsolutePath()); |
| 980 |
} |
| 981 |
} |
| 982 |
|
| 983 |
/** |
| 984 |
* Delete all files in the given directory and all subdirectories. |
| 985 |
* |
| 986 |
* @param dir the name of the directory |
| 987 |
*/ |
| 988 |
protected void delete(String dir) { |
| 989 |
println("Deleting " + dir); |
| 990 |
deleteRecursive(Paths.get(dir)); |
| 991 |
} |
| 992 |
|
| 993 |
/** |
| 994 |
* Delete all files in the list. |
| 995 |
* |
| 996 |
* @param files the name of the files to delete |
| 997 |
*/ |
| 998 |
protected void delete(FileList files) { |
| 999 |
for (Path f : files) { |
| 1000 |
deleteRecursive(f); |
| 1001 |
} |
| 1002 |
} |
| 1003 |
|
| 1004 |
/** |
| 1005 |
* Delete a file or a directory with its content. |
| 1006 |
* |
| 1007 |
* @param file the file or directory to delete |
| 1008 |
*/ |
| 1009 |
public static void deleteRecursive(Path file) { |
| 1010 |
if (Files.exists(file)) { |
| 1011 |
try { |
| 1012 |
Files.walkFileTree(file, new SimpleFileVisitor<Path>() { |
| 1013 |
@Override |
| 1014 |
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { |
| 1015 |
Files.delete(file); |
| 1016 |
return FileVisitResult.CONTINUE; |
| 1017 |
} |
| 1018 |
|
| 1019 |
@Override |
| 1020 |
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { |
| 1021 |
if (exc == null) { |
| 1022 |
Files.delete(dir); |
| 1023 |
return FileVisitResult.CONTINUE; |
| 1024 |
} |
| 1025 |
throw exc; |
| 1026 |
} |
| 1027 |
}); |
| 1028 |
} catch (IOException e) { |
| 1029 |
throw new RuntimeException("Can not delete " + file); |
| 1030 |
} |
| 1031 |
} |
| 1032 |
} |
| 1033 |
|
| 1034 |
/** |
| 1035 |
* Replace each substring in a given string. Regular expression is not used. |
| 1036 |
* |
| 1037 |
* @param s the original text |
| 1038 |
* @param before the old substring |
| 1039 |
* @param after the new substring |
| 1040 |
* @return the string with the string replaced |
| 1041 |
*/ |
| 1042 |
protected static String replaceAll(String s, String before, String after) { |
| 1043 |
int index = 0; |
| 1044 |
while (true) { |
| 1045 |
int next = s.indexOf(before, index); |
| 1046 |
if (next < 0) { |
| 1047 |
return s; |
| 1048 |
} |
| 1049 |
s = s.substring(0, next) + after + s.substring(next + before.length()); |
| 1050 |
index = next + after.length(); |
| 1051 |
} |
| 1052 |
} |
| 1053 |
|
| 1054 |
/** |
| 1055 |
* Print a line to the output unless the quiet mode is enabled. |
| 1056 |
* |
| 1057 |
* @param s the text to write |
| 1058 |
*/ |
| 1059 |
protected void println(String s) { |
| 1060 |
if (!quiet) { |
| 1061 |
sysOut.println(s); |
| 1062 |
} |
| 1063 |
} |
| 1064 |
|
| 1065 |
/** |
| 1066 |
* Print a message to the output unless the quiet mode is enabled. |
| 1067 |
* |
| 1068 |
* @param s the message to write |
| 1069 |
*/ |
| 1070 |
protected void print(String s) { |
| 1071 |
if (!quiet) { |
| 1072 |
sysOut.print(s); |
| 1073 |
} |
| 1074 |
} |
| 1075 |
|
| 1076 |
} |