]> git.argeo.org Git - cc0/argeo-build.git/blob - Make.java
324cae8ab89725ef22d86d545b67a40a70e2dcf2
[cc0/argeo-build.git] / Make.java
1 package org.argeo.build;
2
3 import static java.lang.System.Logger.Level.DEBUG;
4 import static java.lang.System.Logger.Level.ERROR;
5 import static java.lang.System.Logger.Level.INFO;
6 import static java.lang.System.Logger.Level.WARNING;
7
8 import java.io.File;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.OutputStream;
12 import java.io.PrintWriter;
13 import java.lang.System.Logger;
14 import java.lang.System.Logger.Level;
15 import java.lang.management.ManagementFactory;
16 import java.nio.file.DirectoryStream;
17 import java.nio.file.FileVisitResult;
18 import java.nio.file.Files;
19 import java.nio.file.Path;
20 import java.nio.file.PathMatcher;
21 import java.nio.file.Paths;
22 import java.nio.file.SimpleFileVisitor;
23 import java.nio.file.attribute.BasicFileAttributes;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Objects;
31 import java.util.Properties;
32 import java.util.StringJoiner;
33 import java.util.StringTokenizer;
34 import java.util.TreeMap;
35 import java.util.concurrent.CompletableFuture;
36 import java.util.jar.Attributes;
37 import java.util.jar.JarEntry;
38 import java.util.jar.JarOutputStream;
39 import java.util.jar.Manifest;
40 import java.util.zip.Deflater;
41
42 import org.eclipse.jdt.core.compiler.CompilationProgress;
43
44 import aQute.bnd.osgi.Analyzer;
45 import aQute.bnd.osgi.Jar;
46
47 /**
48 * Minimalistic OSGi compiler and packager, meant to be used as a single file
49 * without being itself compiled first. It depends on the Eclipse batch compiler
50 * (aka. ECJ) and the BND Libs library for OSGi metadata generation (which
51 * itselfs depends on slf4j).<br/>
52 * <br/>
53 * For example, a typical system call would be:<br/>
54 * <code>java -cp "/path/to/ECJ jar:/path/to/bndlib jar:/path/to/SLF4J jar" /path/to/cloned/argeo-build/src/org/argeo/build/Make.java action --option1 argument1 argument2 --option2 argument3 </code>
55 */
56 public class Make {
57 private final static Logger logger = System.getLogger(Make.class.getName());
58
59 /**
60 * Environment variable on whether sources should be packaged separately or
61 * integrated in the bundles.
62 */
63 private final static String ENV_SOURCE_BUNDLES = "SOURCE_BUNDLES";
64
65 /**
66 * Environment variable to override the default location for the Argeo Build
67 * configuration files. Typically used if Argeo Build has been compiled and
68 * packaged separately.
69 */
70 private final static String ENV_ARGEO_BUILD_CONFIG = "ARGEO_BUILD_CONFIG";
71
72 /** Name of the local-specific Makefile (sdk.mk). */
73 final static String SDK_MK = "sdk.mk";
74 /** Name of the branch definition Makefile (branch.mk). */
75 final static String BRANCH_MK = "branch.mk";
76
77 /** The execution directory (${user.dir}). */
78 final Path execDirectory;
79 /** Base of the source code, typically the cloned git repository. */
80 final Path sdkSrcBase;
81 /**
82 * The base of the builder, typically a submodule pointing to the public
83 * argeo-build directory.
84 */
85 final Path argeoBuildBase;
86 /** The base of the build for all layers. */
87 final Path sdkBuildBase;
88 /** The base of the build for this layer. */
89 final Path buildBase;
90 /** The base of the a2 output for all layers. */
91 final Path a2Output;
92 /** The base of the a2 sources when packages separately. */
93 final Path a2srcOutput;
94
95 /** Whether sources should be packaged separately */
96 final boolean sourceBundles;
97
98 /** Constructor initialises the base directories. */
99 public Make() throws IOException {
100 sourceBundles = Boolean.parseBoolean(System.getenv(ENV_SOURCE_BUNDLES));
101 if (sourceBundles)
102 logger.log(Level.INFO, "Sources will be packaged separately");
103
104 execDirectory = Paths.get(System.getProperty("user.dir"));
105 Path sdkMkP = findSdkMk(execDirectory);
106 Objects.requireNonNull(sdkMkP, "No " + SDK_MK + " found under " + execDirectory);
107
108 Map<String, String> context = readeMakefileVariables(sdkMkP);
109 sdkSrcBase = Paths.get(context.computeIfAbsent("SDK_SRC_BASE", (key) -> {
110 throw new IllegalStateException(key + " not found");
111 })).toAbsolutePath();
112
113 Path argeoBuildBaseT = sdkSrcBase.resolve("sdk/argeo-build");
114 if (!Files.exists(argeoBuildBaseT)) {
115 String fromEnv = System.getenv(ENV_ARGEO_BUILD_CONFIG);
116 if (fromEnv != null)
117 argeoBuildBaseT = Paths.get(fromEnv);
118 if (fromEnv == null || !Files.exists(argeoBuildBaseT)) {
119 throw new IllegalStateException(
120 "Argeo Build not found. Did you initialise the git submodules or set the "
121 + ENV_ARGEO_BUILD_CONFIG + " environment variable?");
122 }
123 }
124 argeoBuildBase = argeoBuildBaseT;
125
126 sdkBuildBase = Paths.get(context.computeIfAbsent("SDK_BUILD_BASE", (key) -> {
127 throw new IllegalStateException(key + " not found");
128 })).toAbsolutePath();
129 buildBase = sdkBuildBase.resolve(sdkSrcBase.getFileName());
130 a2Output = sdkBuildBase.resolve("a2");
131 a2srcOutput = sdkBuildBase.resolve("a2.src");
132 }
133
134 /*
135 * ACTIONS
136 */
137 /** Compile and create the bundles in one go. */
138 void all(Map<String, List<String>> options) throws IOException {
139 compile(options);
140 bundle(options);
141 }
142
143 /** Compile all the bundles which have been passed via the --bundle argument. */
144 void compile(Map<String, List<String>> options) throws IOException {
145 List<String> bundles = options.get("--bundles");
146 Objects.requireNonNull(bundles, "--bundles argument must be set");
147 if (bundles.isEmpty())
148 return;
149
150 List<String> a2Categories = options.getOrDefault("--dep-categories", new ArrayList<>());
151 List<String> a2Bases = options.getOrDefault("--a2-bases", new ArrayList<>());
152 if (a2Bases.isEmpty() || !a2Bases.contains(a2Output.toString())) {
153 a2Bases.add(a2Output.toString());
154 }
155
156 List<String> compilerArgs = new ArrayList<>();
157
158 Path ecjArgs = argeoBuildBase.resolve("ecj.args");
159 compilerArgs.add("@" + ecjArgs);
160
161 // classpath
162 if (!a2Categories.isEmpty()) {
163 // We will keep only the highest major.minor
164 // and order by bundle name, for predictability
165 Map<String, A2Jar> a2Jars = new TreeMap<>();
166
167 // StringJoiner modulePath = new StringJoiner(File.pathSeparator);
168 for (String a2Base : a2Bases) {
169 categories: for (String a2Category : a2Categories) {
170 Path a2Dir = Paths.get(a2Base).resolve(a2Category);
171 if (!Files.exists(a2Dir))
172 continue categories;
173 // modulePath.add(a2Dir.toString());
174 for (Path jarP : Files.newDirectoryStream(a2Dir,
175 (p) -> p.getFileName().toString().endsWith(".jar"))) {
176 A2Jar a2Jar = new A2Jar(jarP);
177 if (a2Jars.containsKey(a2Jar.name)) {
178 A2Jar current = a2Jars.get(a2Jar.name);
179 if (a2Jar.major > current.major)
180 a2Jars.put(a2Jar.name, a2Jar);
181 else if (a2Jar.major == current.major //
182 // if minor equals, we take the last one
183 && a2Jar.minor >= current.minor)
184 a2Jars.put(a2Jar.name, a2Jar);
185 } else {
186 a2Jars.put(a2Jar.name, a2Jar);
187 }
188 }
189 }
190 }
191
192 StringJoiner classPath = new StringJoiner(File.pathSeparator);
193 for (Iterator<A2Jar> it = a2Jars.values().iterator(); it.hasNext();)
194 classPath.add(it.next().path.toString());
195
196 compilerArgs.add("-cp");
197 compilerArgs.add(classPath.toString());
198 // compilerArgs.add("--module-path");
199 // compilerArgs.add(modulePath.toString());
200 }
201
202 // sources
203 for (String bundle : bundles) {
204 StringBuilder sb = new StringBuilder();
205 Path bundlePath = execDirectory.resolve(bundle);
206 if (!Files.exists(bundlePath)) {
207 if (bundles.size() == 1) {
208 logger.log(WARNING, "Bundle " + bundle + " not found in " + execDirectory
209 + ", assuming this is this directory, as only one bundle was requested.");
210 bundlePath = execDirectory;
211 } else
212 throw new IllegalArgumentException("Bundle " + bundle + " not found in " + execDirectory);
213 }
214 sb.append(bundlePath.resolve("src"));
215 sb.append("[-d");
216 compilerArgs.add(sb.toString());
217 sb = new StringBuilder();
218 sb.append(buildBase.resolve(bundle).resolve("bin"));
219 sb.append("]");
220 compilerArgs.add(sb.toString());
221 }
222
223 if (logger.isLoggable(INFO))
224 compilerArgs.add("-time");
225
226 if (logger.isLoggable(DEBUG)) {
227 logger.log(DEBUG, "Compiler arguments:");
228 for (String arg : compilerArgs)
229 logger.log(DEBUG, arg);
230 }
231
232 boolean success = org.eclipse.jdt.core.compiler.batch.BatchCompiler.compile(
233 compilerArgs.toArray(new String[compilerArgs.size()]), new PrintWriter(System.out),
234 new PrintWriter(System.err), new MakeCompilationProgress());
235 if (!success) // kill the process if compilation failed
236 throw new IllegalStateException("Compilation failed");
237 }
238
239 /** Package the bundles. */
240 void bundle(Map<String, List<String>> options) throws IOException {
241 // check arguments
242 List<String> bundles = options.get("--bundles");
243 Objects.requireNonNull(bundles, "--bundles argument must be set");
244 if (bundles.isEmpty())
245 return;
246
247 List<String> categories = options.get("--category");
248 Objects.requireNonNull(bundles, "--category argument must be set");
249 if (categories.size() != 1)
250 throw new IllegalArgumentException("One and only one --category must be specified");
251 String category = categories.get(0);
252
253 final String branch;
254 Path branchMk = sdkSrcBase.resolve(BRANCH_MK);
255 if (Files.exists(branchMk)) {
256 Map<String, String> branchVariables = readeMakefileVariables(branchMk);
257 branch = branchVariables.get("BRANCH");
258 } else {
259 branch = null;
260 }
261
262 long begin = System.currentTimeMillis();
263 // create jars in parallel
264 List<CompletableFuture<Void>> toDos = new ArrayList<>();
265 for (String bundle : bundles) {
266 toDos.add(CompletableFuture.runAsync(() -> {
267 try {
268 createBundle(branch, bundle, category);
269 } catch (IOException e) {
270 throw new RuntimeException("Packaging of " + bundle + " failed", e);
271 }
272 }));
273 }
274 CompletableFuture.allOf(toDos.toArray(new CompletableFuture[toDos.size()])).join();
275 long duration = System.currentTimeMillis() - begin;
276 logger.log(INFO, "Packaging took " + duration + " ms");
277 }
278
279 /** Package a single bundle. */
280 void createBundle(String branch, String bundle, String category) throws IOException {
281 final Path source;
282 if (!Files.exists(execDirectory.resolve(bundle))) {
283 logger.log(WARNING,
284 "Bundle " + bundle + " not found in " + execDirectory + ", assuming this is this directory.");
285 source = execDirectory;
286 } else {
287 source = execDirectory.resolve(bundle);
288 }
289
290 Path compiled = buildBase.resolve(bundle);
291 String bundleSymbolicName = source.getFileName().toString();
292
293 // Metadata
294 Properties properties = new Properties();
295 Path argeoBnd = argeoBuildBase.resolve("argeo.bnd");
296 try (InputStream in = Files.newInputStream(argeoBnd)) {
297 properties.load(in);
298 }
299
300 if (branch != null) {
301 Path branchBnd = sdkSrcBase.resolve("sdk/branches/" + branch + ".bnd");
302 if (Files.exists(branchBnd))
303 try (InputStream in = Files.newInputStream(branchBnd)) {
304 properties.load(in);
305 }
306 }
307
308 Path bndBnd = source.resolve("bnd.bnd");
309 if (Files.exists(bndBnd))
310 try (InputStream in = Files.newInputStream(bndBnd)) {
311 properties.load(in);
312 }
313
314 // Normalise
315 if (!properties.containsKey("Bundle-SymbolicName"))
316 properties.put("Bundle-SymbolicName", bundleSymbolicName);
317
318 // Calculate MANIFEST
319 Path binP = compiled.resolve("bin");
320 if (!Files.exists(binP))
321 Files.createDirectories(binP);
322 Manifest manifest;
323 try (Analyzer bndAnalyzer = new Analyzer()) {
324 bndAnalyzer.setProperties(properties);
325 Jar jar = new Jar(bundleSymbolicName, binP.toFile());
326 bndAnalyzer.setJar(jar);
327 manifest = bndAnalyzer.calcManifest();
328 } catch (Exception e) {
329 throw new RuntimeException("Bnd analysis of " + compiled + " failed", e);
330 }
331
332 String major = properties.getProperty("major");
333 Objects.requireNonNull(major, "'major' must be set");
334 String minor = properties.getProperty("minor");
335 Objects.requireNonNull(minor, "'minor' must be set");
336
337 // Write manifest
338 Path manifestP = compiled.resolve("META-INF/MANIFEST.MF");
339 Files.createDirectories(manifestP.getParent());
340 try (OutputStream out = Files.newOutputStream(manifestP)) {
341 manifest.write(out);
342 }
343
344 // Load excludes
345 List<PathMatcher> excludes = new ArrayList<>();
346 Path excludesP = argeoBuildBase.resolve("excludes.txt");
347 for (String line : Files.readAllLines(excludesP)) {
348 PathMatcher pathMatcher = excludesP.getFileSystem().getPathMatcher("glob:" + line);
349 excludes.add(pathMatcher);
350 }
351
352 Path bundleParent = Paths.get(bundle).getParent();
353 Path a2JarDirectory = bundleParent != null ? a2Output.resolve(bundleParent).resolve(category)
354 : a2Output.resolve(category);
355 Path jarP = a2JarDirectory.resolve(compiled.getFileName() + "." + major + "." + minor + ".jar");
356 Files.createDirectories(jarP.getParent());
357
358 try (JarOutputStream jarOut = new JarOutputStream(Files.newOutputStream(jarP), manifest)) {
359 jarOut.setLevel(Deflater.DEFAULT_COMPRESSION);
360 // add all classes first
361 Files.walkFileTree(binP, new SimpleFileVisitor<Path>() {
362 @Override
363 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
364 jarOut.putNextEntry(new JarEntry(binP.relativize(file).toString()));
365 Files.copy(file, jarOut);
366 return FileVisitResult.CONTINUE;
367 }
368 });
369
370 // add resources
371 Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
372 @Override
373 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
374 Path relativeP = source.relativize(dir);
375 for (PathMatcher exclude : excludes)
376 if (exclude.matches(relativeP))
377 return FileVisitResult.SKIP_SUBTREE;
378
379 return FileVisitResult.CONTINUE;
380 }
381
382 @Override
383 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
384 Path relativeP = source.relativize(file);
385 for (PathMatcher exclude : excludes)
386 if (exclude.matches(relativeP))
387 return FileVisitResult.CONTINUE;
388 JarEntry entry = new JarEntry(relativeP.toString());
389 jarOut.putNextEntry(entry);
390 Files.copy(file, jarOut);
391 return FileVisitResult.CONTINUE;
392 }
393 });
394
395 Path srcP = source.resolve("src");
396 // Add all resources from src/
397 Files.walkFileTree(srcP, new SimpleFileVisitor<Path>() {
398 @Override
399 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
400 if (file.getFileName().toString().endsWith(".java")
401 || file.getFileName().toString().endsWith(".class"))
402 return FileVisitResult.CONTINUE;
403 jarOut.putNextEntry(new JarEntry(srcP.relativize(file).toString()));
404 if (!Files.isDirectory(file))
405 Files.copy(file, jarOut);
406 return FileVisitResult.CONTINUE;
407 }
408 });
409
410 // add legal notices and licenses
411 for (Path p : listLegalFilesToInclude(source).values()) {
412 jarOut.putNextEntry(new JarEntry(p.getFileName().toString()));
413 Files.copy(p, jarOut);
414 }
415
416 // add sources
417 // TODO add effective BND, Eclipse project file, etc., in order to be able to
418 // repackage
419 if (sourceBundles) {
420 Path a2srcJarDirectory = bundleParent != null ? a2srcOutput.resolve(bundleParent).resolve(category)
421 : a2srcOutput.resolve(category);
422 Files.createDirectories(a2srcJarDirectory);
423 Path srcJarP = a2srcJarDirectory
424 .resolve(compiled.getFileName() + "." + major + "." + minor + ".src.jar");
425 Manifest srcManifest = new Manifest();
426 srcManifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
427 srcManifest.getMainAttributes().putValue("Bundle-SymbolicName", bundleSymbolicName + ".src");
428 srcManifest.getMainAttributes().putValue("Bundle-Version",
429 manifest.getMainAttributes().getValue("Bundle-Version").toString());
430 srcManifest.getMainAttributes().putValue("Eclipse-SourceBundle",
431 bundleSymbolicName + ";version=\"" + manifest.getMainAttributes().getValue("Bundle-Version"));
432
433 try (JarOutputStream srcJarOut = new JarOutputStream(Files.newOutputStream(srcJarP), srcManifest)) {
434 copySourcesToJar(srcP, srcJarOut, "");
435 // add legal notices and licenses
436 for (Path p : listLegalFilesToInclude(source).values()) {
437 jarOut.putNextEntry(new JarEntry(p.getFileName().toString()));
438 Files.copy(p, jarOut);
439 }
440 }
441 } else {
442 copySourcesToJar(srcP, jarOut, "OSGI-OPT/src/");
443 }
444 }
445 }
446
447 /** List the relevant legal files to include, from the SDK source base. */
448 Map<String, Path> listLegalFilesToInclude(Path bundleBase) throws IOException {
449 Map<String, Path> toInclude = new HashMap<>();
450 DirectoryStream<Path> sdkSrcLegal = Files.newDirectoryStream(sdkSrcBase, (p) -> {
451 String fileName = p.getFileName().toString();
452 return switch (fileName) {
453 case "NOTICE":
454 case "LICENSE":
455 case "COPYING":
456 case "COPYING.LESSER":
457 yield true;
458 default:
459 yield false;
460 };
461 });
462 for (Path p : sdkSrcLegal)
463 toInclude.put(p.getFileName().toString(), p);
464 DirectoryStream<Path> bundleLegal = Files.newDirectoryStream(bundleBase, (p) -> {
465 String fileName = p.getFileName().toString();
466 return switch (fileName) {
467 case "NOTICE":
468 case "LICENSE":
469 case "COPYING":
470 case "COPYING.LESSER":
471 yield true;
472 default:
473 yield false;
474 };
475 });
476 // bundle can override
477 for (Path p : bundleLegal)
478 toInclude.put(p.getFileName().toString(), p);
479 return toInclude;
480 }
481
482 /*
483 * UTILITIES
484 */
485 /** Add sources to a jar file */
486 void copySourcesToJar(Path srcP, JarOutputStream srcJarOut, String prefix) throws IOException {
487 Files.walkFileTree(srcP, new SimpleFileVisitor<Path>() {
488 @Override
489 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
490 srcJarOut.putNextEntry(new JarEntry(prefix + srcP.relativize(file).toString()));
491 if (!Files.isDirectory(file))
492 Files.copy(file, srcJarOut);
493 return FileVisitResult.CONTINUE;
494 }
495 });
496 }
497
498 /**
499 * Recursively find the base source directory (which contains the
500 * <code>{@value #SDK_MK}</code> file).
501 */
502 Path findSdkMk(Path directory) {
503 Path sdkMkP = directory.resolve(SDK_MK);
504 if (Files.exists(sdkMkP)) {
505 return sdkMkP.toAbsolutePath();
506 }
507 if (directory.getParent() == null)
508 return null;
509 return findSdkMk(directory.getParent());
510 }
511
512 /**
513 * Reads Makefile variable assignments of the form =, :=, or ?=, ignoring white
514 * spaces. To be used with very simple included Makefiles only.
515 */
516 Map<String, String> readeMakefileVariables(Path path) throws IOException {
517 Map<String, String> context = new HashMap<>();
518 List<String> sdkMkLines = Files.readAllLines(path);
519 lines: for (String line : sdkMkLines) {
520 StringTokenizer st = new StringTokenizer(line, " :=?");
521 if (!st.hasMoreTokens())
522 continue lines;
523 String key = st.nextToken();
524 if (!st.hasMoreTokens())
525 continue lines;
526 String value = st.nextToken();
527 if (st.hasMoreTokens()) // probably not a simple variable assignment
528 continue lines;
529 context.put(key, value);
530 }
531 return context;
532 }
533
534 /** Main entry point, interpreting actions and arguments. */
535 public static void main(String... args) {
536 if (args.length == 0)
537 throw new IllegalArgumentException("At least an action must be provided");
538 int actionIndex = 0;
539 String action = args[actionIndex];
540 if (args.length > actionIndex + 1 && !args[actionIndex + 1].startsWith("-"))
541 throw new IllegalArgumentException(
542 "Action " + action + " must be followed by an option: " + Arrays.asList(args));
543
544 Map<String, List<String>> options = new HashMap<>();
545 String currentOption = null;
546 for (int i = actionIndex + 1; i < args.length; i++) {
547 if (args[i].startsWith("-")) {
548 currentOption = args[i];
549 if (!options.containsKey(currentOption))
550 options.put(currentOption, new ArrayList<>());
551
552 } else {
553 options.get(currentOption).add(args[i]);
554 }
555 }
556
557 try {
558 Make argeoMake = new Make();
559 switch (action) {
560 case "compile" -> argeoMake.compile(options);
561 case "bundle" -> argeoMake.bundle(options);
562 case "all" -> argeoMake.all(options);
563
564 default -> throw new IllegalArgumentException("Unkown action: " + action);
565 }
566
567 long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
568 logger.log(INFO, "Make.java action '" + action + "' succesfully completed after " + (jvmUptime / 1000) + "."
569 + (jvmUptime % 1000) + " s");
570 } catch (Exception e) {
571 long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
572 logger.log(ERROR, "Make.java action '" + action + "' failed after " + (jvmUptime / 1000) + "."
573 + (jvmUptime % 1000) + " s", e);
574 System.exit(1);
575 }
576 }
577
578 static class A2Jar {
579 final Path path;
580 final String name;
581 final int major;
582 final int minor;
583
584 A2Jar(Path path) {
585 this.path = path;
586 String fileName = path.getFileName().toString();
587 fileName = fileName.substring(0, fileName.lastIndexOf('.'));
588 minor = Integer.parseInt(fileName.substring(fileName.lastIndexOf('.') + 1));
589 fileName = fileName.substring(0, fileName.lastIndexOf('.'));
590 major = Integer.parseInt(fileName.substring(fileName.lastIndexOf('.') + 1));
591 name = fileName.substring(0, fileName.lastIndexOf('.'));
592 }
593 }
594
595 /**
596 * An ECJ {@link CompilationProgress} printing a progress bar while compiling.
597 */
598 static class MakeCompilationProgress extends CompilationProgress {
599 private int totalWork;
600 private long currentChunk = 0;
601 private long chunksCount = 80;
602
603 @Override
604 public void worked(int workIncrement, int remainingWork) {
605 if (!logger.isLoggable(Level.INFO)) // progress bar only at INFO level
606 return;
607 long chunk = ((totalWork - remainingWork) * chunksCount) / totalWork;
608 if (chunk != currentChunk) {
609 currentChunk = chunk;
610 for (long i = 0; i < currentChunk; i++) {
611 System.out.print("#");
612 }
613 for (long i = currentChunk; i < chunksCount; i++) {
614 System.out.print("-");
615 }
616 System.out.print("\r");
617 }
618 if (remainingWork == 0)
619 System.out.print("\n");
620 }
621
622 @Override
623 public void setTaskName(String name) {
624 }
625
626 @Override
627 public boolean isCanceled() {
628 return false;
629 }
630
631 @Override
632 public void done() {
633 }
634
635 @Override
636 public void begin(int remainingWork) {
637 this.totalWork = remainingWork;
638 }
639 }
640 }