A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.
Java application-securityappsecbug-bountyburp-alternativeburp-suitedasthttp-proxyinfosecintercepting-proxyjavaowaspowasp-zappenetration-testingpentestingsecuritysecurity-toolsvulnerability-scannerweb-application-securityweb-security
package opensuite.extensions;
import opensuite.core.Debug;
import opensuite.core.SuiteContext;
import opensuite.core.ToolModule;
import opensuite.ui.ToolHost;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.classfile.ClassFile;
import java.lang.classfile.ClassModel;
import java.lang.classfile.constantpool.ClassEntry;
import java.lang.reflect.AccessFlag;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.swing.JMenu;
import javax.swing.SwingUtilities;
/**
* Runs Java extensions loaded at run time: the list under Extensions >
* Installed, and everything that happens to an entry in it.
*
* <p>An extension's code runs only on a thread of its own, which it is given
* when it loads and which is shut down when it is removed. Loading finds the
* entry point by reading the class files, never by loading them; calls
* {@code name}, {@code init}, {@code sink}, {@code tabs}, {@code menus} and
* {@code alwaysTabbed} in turn, each within a time limit; restores any state a
* project has waiting for it; and only then puts it on screen on the event
* thread. A load that fails at any step takes the extension down again and
* leaves its row to say what happened.
*
* <p>Every event the suite raises for an extension is offered to its thread
* from a queue of 256 and returns at once, so an extension cannot hold a suite
* thread. A watchdog marks one whose event runs for more than a few seconds
* unresponsive and pauses new events to it until the owner resumes or removes
* it. Removal unregisters everything first, interrupts the thread, waits for
* it, and closes its class loader; a thread that will not stop is left alone,
* with its loader kept, until the suite restarts. {@code Thread.stop} is never
* called.
*/
public final class ExtensionLoader {
/**
* How long the suite waits. Each wait is paid by a thread of the suite's
* own: the one loading the extension, the one saving a project, the event
* thread at exit. The extension's thread is never left waiting on one; it
* is interrupted when a wait runs out.
*/
public record Timeouts(Duration load, Duration restore, Duration save, Duration shutdown, Duration unresponsive, Duration await) {
/** The suite's own: ten seconds to load or to restore, two to save, five to shut down, five before an extension is marked unresponsive, five for its thread to end. */
public static Timeouts standard() {
return new Timeouts(Duration.ofSeconds(10), Duration.ofSeconds(10), Duration.ofSeconds(2),
Duration.ofSeconds(5), Duration.ofSeconds(5), Duration.ofSeconds(5));
}
}
/** Told on the event thread whenever the list or a row changes. */
public interface Listener { void changed(); }
static final String UNLOADING = "Unloading...", NOT_LOADED = "Not loaded", LOADED = "Loaded", LOADING = "Loading...";
static final String WONT_UNLOAD = "Its thread is still running, so its classes stay loaded until Open Suite is restarted. Nothing more is sent to it.";
/** Settings > Extensions > Startup behavior: load the listed extensions again as the suite starts. */
public static final String RELOAD_ON_STARTUP = "ext.reloadOnStartup";
/** The first line of the list file. */
private static final String LIST_HEADER = "# Open Suite extensions: type, file, auto-reload. Written by Extensions > Installed; edit it only while the suite is closed.";
private final SuiteContext ctx;
private final ToolHost host;
private final Timeouts timeouts;
/** Where the list is kept between runs; null keeps no list. */
private final Path listFile;
private final List<LoadedExtension> items = new CopyOnWriteArrayList<>();
private final List<Listener> listeners = new CopyOnWriteArrayList<>();
private final AtomicLong loads = new AtomicLong();
private volatile boolean closed;
private Thread watchdog;
public ExtensionLoader(SuiteContext ctx, ToolHost host, Path listFile) { this(ctx, host, listFile, Timeouts.standard()); }
public ExtensionLoader(SuiteContext ctx, ToolHost host, Path listFile, Timeouts timeouts) {
this.ctx = ctx;
this.host = host;
this.listFile = listFile;
this.timeouts = timeouts;
}
public Timeouts timeouts() { return timeouts; }
public List<LoadedExtension> items() { return new ArrayList<>(items); }
public void addListener(Listener l) { listeners.add(l); }
// ---- the list ----
/**
* Put an extension in the list and load it on a thread of its own. Returns
* at once. A file that is already in the list is not loaded twice: its row
* is returned.
*/
public LoadedExtension add(String type, File file, boolean autoReload) {
for (LoadedExtension x : items) {
if (sameFile(x.file, file)) {
x.note = "This file is already in the list.";
changed();
return x;
}
}
LoadedExtension x = new LoadedExtension(type, file);
x.autoReload = autoReload;
items.add(x);
saveList();
changed();
start("extension-load-" + loads.incrementAndGet(), () -> load(x));
return x;
}
/**
* Load again, as the suite starts, the extensions listed last time. One
* whose Auto-reload box was ticked loads when "Automatically reload
* extensions on startup" is ticked too; the others are listed and not
* loaded. A file that has moved is listed as not found. Each loads on a
* thread of its own, and joins the window as it is ready.
*/
public void reloadOnStartup() {
for (Saved saved : readList()) {
LoadedExtension x = new LoadedExtension(saved.type(), saved.file());
x.autoReload = saved.autoReload();
items.add(x);
if (x.autoReload && ctx.settings().getBool(RELOAD_ON_STARTUP, true)) {
start("extension-load-" + loads.incrementAndGet(), () -> load(x));
} else {
x.status = NOT_LOADED;
x.done = true;
}
}
changed();
}
/** Take the extension off the suite at once, and off the list once its thread has ended. A thread that will not stop keeps its row, to say so. */
public void remove(LoadedExtension x) {
if (!items.contains(x)) return;
x.removeWanted = true;
detach(x);
start("extension-unload", () -> unload(x));
}
/** The Loaded box: unchecked takes the extension off the suite but keeps its row; checked loads it again, with a new class loader. */
public void setLoaded(LoadedExtension x, boolean loaded) {
if (loaded) {
if (x.module != null || LOADING.equals(x.status)) return;
// A thread that would not stop still holds the previous copy; a second would only add to it.
if (x.thread != null) {
x.note = "Its earlier copy is still running, so it cannot be loaded again until Open Suite is restarted.";
changed();
return;
}
reload(x);
return;
}
if (LOADING.equals(x.status)) { x.status = UNLOADING; changed(); return; }
if (x.module == null) return;
x.removeWanted = false;
detach(x);
start("extension-unload", () -> unload(x));
}
/** Let an unresponsive extension take events again. One that is not running has nothing to resume. */
public void resume(LoadedExtension x) {
ExtensionThread thread = x.thread;
if (thread == null || !x.unresponsive || x.module == null) return;
thread.resume();
x.unresponsive = false;
x.status = LOADED;
x.note = "";
changed();
}
/** The Auto-reload box: whether the extension loads again as the suite starts. */
public void setAutoReload(LoadedExtension x, boolean on) { x.autoReload = on; saveList(); changed(); }
/** Move the extension up or down the list. */
public void move(LoadedExtension x, int delta) {
int from = items.indexOf(x), to = from + delta;
if (from < 0 || to < 0 || to >= items.size()) return;
items.remove(from);
items.add(to, x);
saveList();
changed();
}
/** Take every extension off the suite without waiting, and stop the watchdog. For a suite that is closing, and for tests. */
public void close() {
closed = true;
for (LoadedExtension x : items) {
detach(x);
ExtensionThread thread = x.thread;
if (thread != null) { thread.unregisterEverything(); thread.shutdownNow(); }
}
items.clear();
changed();
}
// ---- loading ----
private void reload(LoadedExtension x) {
x.status = LOADING;
x.note = "";
x.unresponsive = false;
x.done = false;
changed();
start("extension-load-" + loads.incrementAndGet(), () -> load(x));
}
private void load(LoadedExtension x) {
try { loadOnThread(x); }
catch (Throwable t) { fail(x, "Failed: " + t, "Loading it failed: " + t); }
finally {
x.done = true;
changed();
}
}
private void loadOnThread(LoadedExtension x) throws Exception {
if (!x.file.isFile()) { fail(x, "File not found", "No such file: " + x.file); return; }
if (!"Java".equals(x.type)) {
fail(x, "Failed", x.type + " extensions need a " + x.type + " runtime; set its location under Settings > Extensions.");
return;
}
Entry entry;
try (JarFile jar = new JarFile(x.file)) { entry = findEntryPoint(jar); }
catch (java.util.zip.ZipException e) {
// No end to the zip: empty, cut short in copying, or turned into text on the way here.
fail(x, "Failed: not a complete jar", x.file.getName() + " is " + x.file.length() + " bytes and is not a complete jar ("
+ e.getMessage() + "). It may be empty, cut short in copying, or not a jar at all.");
return;
} catch (IOException e) {
fail(x, "Failed: " + e, x.file.getName() + " could not be read: " + e);
return;
}
if (entry.name() == null) { fail(x, "No entry point", entry.problem()); return; }
ExtensionClassLoader loader = new ExtensionClassLoader(classPath(x));
x.loader = loader;
x.entryClass = entry.name().replace('/', '.');
ExtensionThread thread = new ExtensionThread(x, ctx);
loader.bind(thread);
x.thread = thread;
thread.onTerminated = () -> threadEnded(x, thread);
ensureWatchdog();
ExtensionThread.Attempt<Object> made = thread.call("loading " + x.entryClass,
() -> Class.forName(x.entryClass, true, loader).getDeclaredConstructor().newInstance(), timeouts.load().toMillis());
if (!made.ok()) { giveUp(x, made, "loading " + x.entryClass); return; }
if (!(made.value() instanceof ToolModule target)) {
fail(x, "Failed: not a tool", x.entryClass + " does not implement opensuite.core.ToolModule.");
return;
}
x.target = target;
ExtensionThread.Attempt<String> named = thread.call("name()", target::name, timeouts.load().toMillis());
if (!named.ok()) { giveUp(x, named, "name()"); return; }
String problem = nameProblem(named.value());
if (problem != null) { fail(x, "Failed: " + problem, "It names itself " + named.value() + "."); return; }
x.name = named.value().trim();
thread.rename(x.name);
ExtensionThread.Attempt<Void> init = thread.call("init()", () -> { target.init(ctx); return null; }, timeouts.load().toMillis());
if (init.timedOut()) { disable(x, "init() did not finish in " + duration(timeouts.load())); return; }
if (init.failed()) { fail(x, "Failed: init() threw", "Its Errors tab has the trace."); return; }
x.initialised = true;
// The sink it declares is registered under its own name; singleItem was read on its thread.
ExtensionThread.Attempt<SuiteContext.MessageSink> sink = thread.call("sink()", () -> {
SuiteContext.MessageSink declared = target.sink();
return declared == null ? null : thread.sink(declared);
}, timeouts.load().toMillis());
if (!sink.ok()) { giveUp(x, sink, "sink()"); return; }
if (sink.value() != null) { ctx.registerSink(x.name, sink.value()); x.sinkUnder = x.name; }
ExtensionThread.Attempt<ToolModule.Tab[]> built = thread.call("tabs()", target::tabs, timeouts.load().toMillis());
if (!built.ok()) { giveUp(x, built, "tabs()"); return; }
String bad = tabsProblem(built.value());
if (bad != null) { fail(x, "Failed: " + bad, null); return; }
ExtensionThread.Attempt<JMenu[]> menus = thread.call("menus()", target::menus, timeouts.load().toMillis());
if (!menus.ok()) { giveUp(x, menus, "menus()"); return; }
ExtensionThread.Attempt<Boolean> tabbed = thread.call("alwaysTabbed()", target::alwaysTabbed, timeouts.load().toMillis());
if (!tabbed.ok()) { giveUp(x, tabbed, "alwaysTabbed()"); return; }
// A state the project saved for it before it was loaded.
java.io.Serializable held = ctx.takeHeldToolState(x.name);
if (held != null) {
ExtensionThread.Attempt<Void> back = thread.call("restoreState()", () -> { target.restoreState(held); return null; }, timeouts.restore().toMillis());
if (back.timedOut()) { disable(x, "restoring its saved state did not finish in " + duration(timeouts.restore())); return; }
// One that threw is on the row; the extension comes up without its saved state.
}
if (UNLOADING.equals(x.status)) { disable(x, "it was taken down while it was loading"); return; }
GuardedModule module = new GuardedModule(this, ctx, x, target, built.value(), menus.value(),
tabbed.value() != null && tabbed.value());
x.module = module;
x.impact = measureImpact(x.file);
x.say("Loaded " + x.entryClass + " as " + x.name + " (" + thread.threadName() + ").");
onEventThread(x, "put on screen", () -> {
// The shell enters the module in the context, as it does for a built-in tool.
host.toolAdded(module);
x.status = LOADED;
x.note = "";
x.loaded = true;
changed();
});
}
/** A failed load: nothing of the extension stays on the suite, and the row says what happened. */
private void fail(LoadedExtension x, String status, String detail) {
if (detail != null) x.errors.line(status + ". " + detail);
x.status = status;
x.note = detail == null ? "" : detail;
x.loaded = false;
takeDown(x);
changed();
}
/** An extension that did not finish a call in time: taken down, and off the suite if it had got that far, with the row saying why. */
void disable(LoadedExtension x, String why) {
if (x.module != null) detach(x);
x.status = "Disabled: " + why;
x.note = "It was taken down.";
x.loaded = false;
x.errors.line(x.status + ". " + x.note);
takeDown(x);
changed();
}
private void giveUp(LoadedExtension x, ExtensionThread.Attempt<?> attempt, String doing) {
if (attempt.timedOut()) disable(x, doing + " did not finish in " + duration(timeouts.load()));
else fail(x, "Failed: " + doing + " threw", "Its Errors tab has the trace.");
}
// ---- unloading ----
/** The suite lets go at once: its tab, menus, tool registration and sink are gone before this returns. */
private void detach(LoadedExtension x) {
GuardedModule module = x.module;
if (module != null) {
// The shell takes the module out of the context as it takes it off screen.
onEventThread(x, "taken off screen", () -> host.toolRemoved(module));
x.module = null;
}
if (x.sinkUnder != null) { ctx.unregisterSink(x.sinkUnder); x.sinkUnder = null; }
x.loaded = false;
// Whether it was unresponsive is left as it is: a thread that is stuck stays stuck while it goes,
// and the watchdog and the unload both go by that.
x.status = UNLOADING;
x.note = "";
changed();
}
/** What is left once the suite has let go: everything the extension registered is unregistered, its thread is interrupted and waited for, and its loader is closed. */
private void unload(LoadedExtension x) {
boolean alive = takeDown(x);
if (alive) {
// Its row stays, to say so; it goes once the thread has ended.
x.note = WONT_UNLOAD;
} else if (!x.removeWanted && UNLOADING.equals(x.status)) {
x.status = NOT_LOADED;
}
if (!alive && x.removeWanted) {
items.remove(x);
saveList();
}
changed();
}
/** Unregister what the extension registered, interrupt its thread, wait for it, and close its loader unless the thread is still alive. Returns whether it is. */
private boolean takeDown(LoadedExtension x) {
ExtensionThread thread = x.thread;
if (thread == null) return false;
// First, so that nothing is offered to the extension on its way out.
thread.unregisterEverything();
ToolModule target = x.target;
if (x.initialised && target != null && !x.unresponsive) {
// One that is unresponsive cannot run it, and waiting would only cost the limit.
thread.call("shutdown()", () -> { target.shutdown(); return null; }, timeouts.shutdown().toMillis());
}
thread.shutdownNow();
boolean alive;
try { alive = !thread.awaitTermination(timeouts.await().toMillis()); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); alive = thread.isAlive(); }
x.target = null;
x.initialised = false;
x.thread = alive ? thread : null;
if (alive) { x.status = "Won't unload until restart"; x.note = WONT_UNLOAD; }
else closeLoader(x);
return alive;
}
private void threadEnded(LoadedExtension x, ExtensionThread thread) {
closeLoader(x);
if (x.thread != thread) return;
x.thread = null;
if (WONT_UNLOAD.equals(x.note)) {
x.note = "Its thread has ended, so its classes are released.";
if (!x.removeWanted) x.status = NOT_LOADED;
}
// Remove was asked for and had to wait for the thread: now the row goes.
if (x.removeWanted && items.remove(x)) saveList();
changed();
}
private void closeLoader(LoadedExtension x) {
ExtensionClassLoader loader = x.loader;
if (x.loaderClosed || loader == null) return;
try { loader.close(); }
catch (IOException e) { Debug.error("the class loader of extension '" + x.name + "' could not be closed", e); }
x.loaderClosed = true;
}
// ---- the watchdog ----
private void ensureWatchdog() {
synchronized (this) {
if (closed || (watchdog != null && watchdog.isAlive())) return;
watchdog = new Thread(this::watch, "opensuite-ext-watchdog");
watchdog.setDaemon(true);
watchdog.start();
}
}
private void watch() {
long poll = Math.max(20L, timeouts.unresponsive().toMillis() / 8);
while (!closed) {
for (LoadedExtension x : items) {
ExtensionThread thread = x.thread;
if (thread == null || x.unresponsive) continue;
long ran = thread.runningMillis();
if (ran >= timeouts.unresponsive().toMillis()) markUnresponsive(x, ran);
}
try { Thread.sleep(poll); }
catch (InterruptedException e) { return; }
}
}
private void markUnresponsive(LoadedExtension x, long ranMillis) {
ExtensionThread thread = x.thread;
if (thread == null) return;
// Events are paused first, and the flag that says so is raised last:
// whoever sees the flag sees everything else done.
thread.pause();
String why = "a call has been running for " + duration(Duration.ofMillis(ranMillis));
if (x.module != null) x.status = "Unresponsive";
x.note = "It is unresponsive: " + why + ", so new events to it are paused until it is removed or resumed.";
x.errors.line(x.note);
Debug.error("extension '" + x.name + "' is unresponsive: " + why, null);
ctx.alert("extensions", "Extension " + x.name + " is unresponsive: " + why + ". New events to it are paused.");
x.unresponsive = true;
changed();
}
// ---- the list between runs ----
/** One line of the list. */
private record Saved(String type, File file, boolean autoReload) {}
/** The list as it was left: type, file and whether it loads again, one per line. */
private List<Saved> readList() {
List<Saved> out = new ArrayList<>();
if (listFile == null || !Files.isRegularFile(listFile)) return out;
try {
for (String line : Files.readAllLines(listFile, StandardCharsets.UTF_8)) {
if (line.isBlank() || line.startsWith("#")) continue;
String[] fields = line.split("\t", -1);
if (fields.length < 2) continue;
out.add(new Saved(fields[0], new File(fields[1]), fields.length > 2 && Boolean.parseBoolean(fields[2])));
}
} catch (IOException e) {
Debug.error("the list of extensions could not be read from " + listFile, e);
}
return out;
}
/** Write the list beside itself and move it into place, so a crash while it is written leaves the old list. */
private synchronized void saveList() {
if (listFile == null || closed) return;
StringBuilder text = new StringBuilder(LIST_HEADER).append('\n');
for (LoadedExtension x : items) {
text.append(x.type).append('\t').append(x.file.getAbsolutePath()).append('\t').append(x.autoReload).append('\n');
}
try {
Path beside = listFile.resolveSibling(listFile.getFileName() + ".saving");
if (listFile.getParent() != null) Files.createDirectories(listFile.getParent());
Files.writeString(beside, text.toString(), StandardCharsets.UTF_8);
try {
Files.move(beside, listFile, java.nio.file.StandardCopyOption.REPLACE_EXISTING, java.nio.file.StandardCopyOption.ATOMIC_MOVE);
} catch (java.nio.file.AtomicMoveNotSupportedException e) {
Files.move(beside, listFile, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
Debug.error("the list of extensions could not be written to " + listFile, e);
}
}
// ---- helpers ----
/** The entry point of a jar, or what stopped there being one. */
private record Entry(String name, String problem) {
static Entry none(String problem) { return new Entry(null, problem); }
}
/** What the row says when no class of the jar can be the entry point. */
private static final String NO_ENTRY = "No class in the jar implements opensuite.core.ToolModule.";
/**
* The class to run, as the one that implements {@code ToolModule} and can
* be built. The class files are read, never loaded. One candidate is the
* entry point; of several, {@code META-INF/services/opensuite.core.ToolModule}
* must name one. No name when there is none or the jar does not say which.
*/
static Entry findEntryPoint(JarFile jar) throws IOException {
final String contract = ToolModule.class.getName().replace('.', '/');
Map<String, ClassModel> classes = new LinkedHashMap<>();
for (JarEntry entry : Collections.list(jar.entries())) {
String n = entry.getName();
if (!n.endsWith(".class") || n.startsWith("META-INF/") || n.endsWith("module-info.class")) continue;
ClassModel model;
try (InputStream in = jar.getInputStream(entry)) { model = ClassFile.of().parse(in.readAllBytes()); }
catch (RuntimeException notReadable) { continue; }
classes.put(model.thisClass().asInternalName(), model);
}
LinkedHashSet<String> candidates = new LinkedHashSet<>();
for (String name : classes.keySet()) {
ClassModel model = classes.get(name);
if (model.flags().has(AccessFlag.INTERFACE) || model.flags().has(AccessFlag.ABSTRACT)) continue;
boolean buildable = model.methods().stream().anyMatch(m ->
m.methodName().equalsString("<init>") && m.methodTypeSymbol().parameterCount() == 0 && m.flags().has(AccessFlag.PUBLIC));
if (buildable && inherits(name, contract, classes, new HashSet<>())) candidates.add(name);
}
if (candidates.isEmpty()) return Entry.none(NO_ENTRY);
if (candidates.size() == 1) return new Entry(candidates.iterator().next(), null);
JarEntry named = jar.getJarEntry("META-INF/services/" + ToolModule.class.getName());
if (named != null) {
try (BufferedReader r = new BufferedReader(new InputStreamReader(jar.getInputStream(named), StandardCharsets.UTF_8))) {
for (String line : r.lines().toList()) {
String want = line.strip();
if (want.isEmpty() || want.startsWith("#")) continue;
String internal = want.replace('.', '/');
if (candidates.contains(internal)) return new Entry(internal, null);
}
}
}
List<String> names = new ArrayList<>();
for (String c : candidates) names.add(c.replace('/', '.'));
return Entry.none("More than one class in the jar implements opensuite.core.ToolModule (" + String.join(", ", names)
+ ") and META-INF/services/opensuite.core.ToolModule does not say which to run.");
}
/** Whether the class implements the contract itself or through a class or interface above it, within this jar. */
private static boolean inherits(String name, String contract, Map<String, ClassModel> classes, Set<String> seen) {
if (name.equals(contract)) return true;
if (!seen.add(name)) return false;
ClassModel model = classes.get(name);
// Not in this jar: the suite's or a library's, and the contract is only in the suite.
if (model == null) return false;
for (ClassEntry i : model.interfaces()) if (inherits(i.asInternalName(), contract, classes, seen)) return true;
return model.superclass().map(s -> inherits(s.asInternalName(), contract, classes, seen)).orElse(false);
}
/** Why the extension may not go by this name, or null when it may. */
private String nameProblem(String name) {
if (name == null) return "name() returned nothing";
String n = name.trim();
if (n.isEmpty()) return "its name is blank";
if (n.equalsIgnoreCase("scanner")) return "the name \"scanner\" is reserved";
for (ToolModule t : ctx.tools()) if (t.name().equalsIgnoreCase(n)) return "the name \"" + n + "\" is already used by a tool";
if (ctx.sinkNames().contains(n)) return "the name \"" + n + "\" is already a Send to destination";
return null;
}
/** Settings > Extensions > Java environment: a folder of library jars every extension has on its class path. */
public static final String JAVA_LIBS = "ext.javaLibs";
/** The extension's own jar, then every jar of the library folder, by name. */
private URL[] classPath(LoadedExtension x) throws IOException {
List<URL> urls = new ArrayList<>();
urls.add(x.file.toURI().toURL());
String folder = ctx.settings().get(JAVA_LIBS, "");
if (!folder.isBlank()) {
File[] jars = new File(folder).listFiles((dir, name) -> name.endsWith(".jar"));
if (jars == null) {
x.errors.line("The library folder " + folder + " is not a folder, so no library jars were added to the class path.");
} else {
java.util.Arrays.sort(jars, java.util.Comparator.comparing(File::getName));
for (File jar : jars) urls.add(jar.toURI().toURL());
if (jars.length > 0) x.say(jars.length + " library jars on its class path from " + folder + ".");
}
}
return urls.toArray(new URL[0]);
}
/** Why the tabs cannot be shown, or null when they can. */
private static String tabsProblem(ToolModule.Tab[] tabs) { if (tabs == null) return "tabs() returned nothing";
if (tabs.length == 0) return "it declares no tabs";
for (int i = 0; i < tabs.length; i++) {
ToolModule.Tab t = tabs[i];
if (t == null || t.component() == null) return "its tab " + (i + 1) + " has no component";
if (t.title() == null || t.title().isBlank()) return "its tab " + (i + 1) + " has no title";
}
return null;
}
/** A limit as the row writes it. */
static String duration(Duration limit) {
return limit.toMillis() < 1000 ? limit.toMillis() + " ms" : limit.toSeconds() + " seconds";
}
/**
* A rough system-impact score from the extension's own size: a bigger jar
* with more classes loads more code and costs more to run. It is a measure
* of the file, not a prediction about behaviour, which is why it is called
* an estimate everywhere it is shown.
*/
static int measureImpact(File jar) {
if (jar == null || !jar.isFile()) return 0;
long kb = jar.length() / 1024;
int classes = 0;
try (JarFile jf = new JarFile(jar)) {
for (JarEntry entry : Collections.list(jf.entries())) if (entry.getName().endsWith(".class")) classes++;
} catch (IOException ignored) { }
int score = (int) Math.min(60, kb / 40) + Math.min(40, classes / 10);
return Math.max(1, Math.min(100, score));
}
private static boolean sameFile(File a, File b) {
try { return a.getCanonicalFile().equals(b.getCanonicalFile()); }
catch (IOException e) { return a.getAbsolutePath().equals(b.getAbsolutePath()); }
}
private void start(String name, Runnable work) {
Thread t = new Thread(() -> {
try { work.run(); }
catch (Throwable e) { Debug.error("extension work failed on " + name, e); }
}, name);
t.setDaemon(true);
t.start();
}
/** Run on the event thread: now if already there, otherwise before this returns. */
private void onEventThread(LoadedExtension x, String doing, Runnable work) {
if (SwingUtilities.isEventDispatchThread()) { work.run(); return; }
try { SwingUtilities.invokeAndWait(work); }
catch (InvocationTargetException e) { Debug.error("the shell could not " + doing + " extension '" + x.name + "'", e.getCause() == null ? e : e.getCause()); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
private void changed() {
if (listeners.isEmpty()) return;
Runnable tell = () -> { for (Listener l : listeners) l.changed(); };
if (SwingUtilities.isEventDispatchThread()) tell.run();
else SwingUtilities.invokeLater(tell);
}
}