1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
package com.it_jaros.networkScanner;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class ProgressBar {
private final ScheduledExecutorService ui = Executors.newSingleThreadScheduledExecutor();
private final ReentrantLock lock = new ReentrantLock();
private List<Progress> hosts;
public void start() {
this.hosts = new ArrayList<>();
System.out.print("Scanning targets...\n\n");
ui.scheduleAtFixedRate(() -> {
lock.lock();
drawProgress(false);
lock.unlock();
}, 1, 200, TimeUnit.MILLISECONDS);
}
private void drawProgress(boolean last) {
// paint a bar per host
for (Progress progress : hosts) {
drawBar(progress);
}
if (!last) {
// move cursor up again
System.out.print("\u001b[" + hosts.size() + "A");
}
}
public void submit(Progress progress) {
lock.lock();
hosts.add(progress);
lock.unlock();
}
private void drawBar(Progress progress) {
System.out.print("\u001b[2K\r");
System.out.println(createBar(
progress.host(),
progress.open().get(),
progress.done().get(),
progress.total()));
}
public String createBar(String label, int open, int done, int total) {
int width = 30;
double pct = total == 0 ? 1.0 : (done / (double) total);
int filled = (int) (pct * width);
String brackets = "[" + "#".repeat(filled) + "-".repeat(width - filled) + "]";
int percent = (int) (pct * 100);
return String.format("%-40s open=%s %s %3d%% (%d/%d)", label, open, brackets, percent, done, total);
}
public void stop() {
ui.shutdown();
try {
ui.awaitTermination(10, TimeUnit.SECONDS);
// we need to draw one last time for the 100% to appear
drawProgress(true);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
}
}
|