Class SNTUtils
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final recordHandle to a task submitted viasubmitBackground(java.util.concurrent.Callable<T>, java.lang.String): the runningFutureplus the single-threadExecutorServicebacking it, so a caller can wait on the same future repeatedly (e.g. across a retry-prompt loop) and cancel/shut it down exactly once when done with it.static final recordSnapshot of JVM heap usage in MB, derived from a singleRuntimeread. -
Field Summary
Fields -
Method Summary
Modifier and TypeMethodDescriptionstatic voidstatic voidcsvQuoteAndPrint(PrintWriter pw, Object o) static FiledownloadAndExtractZip(String zipUrl) Downloads a zip archive from the specified URL and extracts it to a fresh temporary directory.static FiledownloadToTempFile(String fileUrl) Downloads a file from the specified URL to a temporary filestatic voidstatic voidAserror(String), but allows suppressing the notification-center mirroring, e.g., when the caller has already surfaced the message to the user synchronously (a modal dialog)static voidstatic voidAserror(String, Throwable), but allows suppressing the notification-center mirroring, e.g., when the caller has already surfaced the message to the user synchronously (a modal dialog)static StringextractReadableTimeStamp(File file) static booleanfileAvailable(File file) static FilefindClosestPair(File file, String pairExt) static FilefindClosestPair(File file, String[] pairExts) static StringformatBytes(long bytes) static StringformatDouble(double value, int digits) getBackupCopies(File location) Returns all timestamped backup copies in the specified location.getBackupCopies(File location, String baseName) Returns timestamped backup copies of traces files in the specified location.static FileReturns SNT's own scratch/cache directory, used by disk-backed operations (e.g.static longComputes the on-disk size ofgetCacheDir().static org.scijava.ContextConvenience method to access the context of the running Fiji instancestatic DecimalFormatgetDecimalFormat(double value, int digits) static StringgetElapsedTime(long fromStart) static SNTUtils.HeapInfostatic SNTstatic StringgetLastElement(String filePathOrUrlOrCloudLink) Extracts the last path/URL element (typically a filename) from a file path, URL, or cloud-storage link, e.g.,"/data/sample.n5"or"https://host/a/b.zarr?x=1"both yield"b.zarr"/"sample.n5".static SNTDeprecated.static Stringstatic File[]getReconstructionFiles(File dir, String pattern) Retrieves a list of reconstruction files stored in a common directory matching the specified criteria.static StringgetSanitizedUnit(String unit) static Stringstatic FilegetUniquelySuffixedFile(File referenceFile) static FilegetUniquelySuffixedFile(File referenceFile, String forcedExtension) static FilegetUniquelySuffixedTifFile(File referenceFile) static booleanstatic booleanAssesses if SNT is running in debug modestatic booleanisReachable(String url, int timeoutMs) Checks for whetherurl's host can be reached, meant to be called before a real download/stream attempt (e.g.,downloadToTempFile(java.lang.String)) so that a missing network connection surfaces as one clear message.static booleanisReconstructionFile(File file) static booleanReturns whether the current context was self-initialized by SNT (i.e., no host application like ImageJ/Fiji provided one).protected static booleanisValidURL(String url) static voidstatic LocalDateTimeReturns the current date-time truncated to whole seconds, e.g., for stamping exported content with a generation time.static InputStreamopenRemoteStream(String url) Opens anInputStreamtourlwith explicit connect/read timeouts, so a stalled or unreachable remote host fails with a clearIOExceptioninstead of hanging indefinitely - the default behavior ofURL.openStream(), whose underlyingURLConnectionhas no timeout at all unless one is set explicitly.Generates a list of random paths.static voidremoveViewer(Viewer3D viewer) static <T> TrunWithTimeout(Callable<T> task, long timeoutSeconds, String description) Runstaskon a bounded background (daemon) thread, guarding against blocking I/O - typically remote N5/Zarr discovery, that can otherwise hang indefinitely on a stalled connection with no feedback to the user.static StringsanitizeFilename(String filename) Replaces characters that are unsafe/reserved in filenames with an underscore, leaving alphanumerics, dots, and hyphens untouched.static voidsetContext(org.scijava.Context context) static voidsetDebugMode(boolean b) Enables/disables debug modestatic voidsetIsLoading(boolean isLoading, boolean streamMode) Shows or hides the loading splash screen.protected static voidstatic SNTstartApp()Convenience method to start up SNT's GUI in 'standard' mode.static SNTstartApp(boolean streamMode) Convenience method to start up SNT's GUI.static StringstripExtension(String filename) static <T> SNTUtils.BackgroundTask<T> submitBackground(Callable<T> task, String threadName) Submitstaskto a bounded background (daemon) thread and returns immediately with a handle to it, instead of waiting for it likerunWithTimeout(java.util.concurrent.Callable<T>, long, java.lang.String)does.static void
-
Field Details
-
TIMESTAMP_REGEX
- See Also:
-
VERSION
-
-
Method Details
-
getReadableVersion
-
addViewer
-
removeViewer
-
getViewers
-
error
-
error
Aserror(String), but allows suppressing the notification-center mirroring, e.g., when the caller has already surfaced the message to the user synchronously (a modal dialog)- Parameters:
string- the messagequeueNotice- whether to also mirror the message into the notification-center queue
-
setPlugin
-
getPluginInstance
Deprecated.usegetInstance()instead -
getInstance
-
error
-
error
Aserror(String, Throwable), but allows suppressing the notification-center mirroring, e.g., when the caller has already surfaced the message to the user synchronously (a modal dialog)- Parameters:
string- the messaget- the associated exception, or nullqueueNotice- whether to also mirror the message into the notification-center queue
-
log
-
warn
-
csvQuoteAndPrint
-
stripExtension
-
sanitizeFilename
Replaces characters that are unsafe/reserved in filenames with an underscore, leaving alphanumerics, dots, and hyphens untouched.- Parameters:
filename- the candidate filename (or a full path -- only used for e.g. a whole path rather than a bare filename component; separators are not treated specially and will themselves be replaced)- Returns:
- the sanitized filename, or null if
filenameis null
-
getLastElement
Extracts the last path/URL element (typically a filename) from a file path, URL, or cloud-storage link, e.g.,"/data/sample.n5"or"https://host/a/b.zarr?x=1"both yield"b.zarr"/"sample.n5". Handles Windows-style backslashes, trailing slashes, and URL query parameters/anchors.- Parameters:
filePathOrUrlOrCloudLink- the path/URL/link to parse- Returns:
- the last element, or an empty string if
filePathOrUrlOrCloudLinkis null or blank
-
getCacheDir
Returns SNT's own scratch/cache directory, used by disk-backed operations (e.g.DiskBackedStorageBackend,Lazy). Unlike the workspace directory (seeSNTPrefs#getWorkspaceDir()), this directory holds only disposable, regenerable scratch data -- never anything a user created -- so it lives under the OS temp root.Individual operations create their own uniquely-named subdirectory here and clean up after themselves once done. This parent directory itself is created lazily and left in place across sessions, so that (1) it is always at the same, discoverable path and (2) leftovers from a crashed session (which skipped its own cleanup) remain visible and removable.
- Returns:
- SNT's cache directory (created if it did not already exist), or, if that path could
not be created/written to (e.g. permissions, a network-mounted or read-only temp
location, a stray file already occupying that path), a fallback directory under the
user's home folder. Callers relying on this directory for disk-backed caching should
still be prepared for
IOExceptions down the line (e.g. if the disk is full).
-
getHeapInfo
- Returns:
- a snapshot of current JVM heap usage
-
formatBytes
- Parameters:
bytes- a byte count- Returns:
- a human-readable representation (e.g., "12.3 MB")
-
getCacheDirSize
public static long getCacheDirSize()Computes the on-disk size ofgetCacheDir(). This walks the whole cache tree, so it can be slow once many files have accumulated; avoid calling this on the EDT- Returns:
- the cache directory's size in bytes, or 0 if it could not be read
-
getUniquelySuffixedTifFile
-
getUniquelySuffixedFile
-
getUniquelySuffixedFile
-
fileAvailable
-
isValidURL
-
isReachable
Checks for whetherurl's host can be reached, meant to be called before a real download/stream attempt (e.g.,downloadToTempFile(java.lang.String)) so that a missing network connection surfaces as one clear message. est-effort: only http(s) URLs are actually probed; any other scheme (e.g. a bare host-less URI) is assumed reachable, deferring to the real caller- Parameters:
url- the URL to checktimeoutMs- connect timeout, in milliseconds- Returns:
- true if the host could be reached (or
urlis not a plain http(s) URL); false if a connection could not be established withintimeoutMs
-
formatDouble
-
getDecimalFormat
-
isDebugMode
public static boolean isDebugMode()Assesses if SNT is running in debug mode- Returns:
- the debug flag
-
setDebugMode
public static void setDebugMode(boolean b) Enables/disables debug mode- Parameters:
b- verbose flag
-
findClosestPair
-
findClosestPair
-
getSanitizedUnit
-
randomPaths
Generates a list of random paths. Only useful for debugging purposes- Returns:
- the list of random Paths
-
getElapsedTime
-
getReconstructionFiles
Retrieves a list of reconstruction files stored in a common directory matching the specified criteria.- Parameters:
dir- the directory containing the reconstruction files (.(e)swc, .traces, .json extension)pattern- the filename substring (case-sensitive) to be matched. Only filenames containingpatternwill be imported from the directory.nullallowed.- Returns:
- the array of files. An empty list is retrieved if
diris not a valid, readable directory.
-
isReconstructionFile
-
getBackupCopies
Returns timestamped backup copies of traces files in the specified location. Searches both the given directory (legacy behavior) and the snt_backups subdirectory implemented in SNTv5.- Parameters:
location- the directory to search for backup filesbaseName- the base filename prefix to match (e.g., "OP_1" to match "OP_1_2026-01-30_10-00-00.traces"), or null to match all traces files with timestamps- Returns:
- list of backup files (never null, may be empty), sorted most recent first
-
getBackupCopies
Returns all timestamped backup copies in the specified location. Convenience method that matches all traces files with timestamps.- Parameters:
location- the directory to search for backup files- Returns:
- list of backup files (never null, may be empty), sorted most recent first
-
nowTruncatedToSeconds
Returns the current date-time truncated to whole seconds, e.g., for stamping exported content with a generation time. -
getTimeStamp
-
extractReadableTimeStamp
-
setIsLoading
public static void setIsLoading(boolean isLoading, boolean streamMode) Shows or hides the loading splash screen. Calls nest safely: several independent call chains can be "loading" at once, so the splash only actually closes once everytruehas been balanced by a matchingfalse, hence calls should be made in a try/finally block.- Parameters:
isLoading- true to show the splash screen (or register one more caller that wants it showing, if already showing); false to release one such registration, closing the splash once no callers still hold itstreamMode- true for the wide "SNT Stream" layout, false for the default one
-
openRemoteStream
Opens anInputStreamtourlwith explicit connect/read timeouts, so a stalled or unreachable remote host fails with a clearIOExceptioninstead of hanging indefinitely - the default behavior ofURL.openStream(), whose underlyingURLConnectionhas no timeout at all unless one is set explicitly. Used for remote reconstruction/marker/demo files (e.g.https://.../autotracings.traces), which are typically small enough that a single bounded connection (rather thanrunWithTimeout(java.util.concurrent.Callable<T>, long, java.lang.String)'s background-thread wrapper) is enough.- Parameters:
url- the URL to open (e.g. a remote .traces/.csv file, or a .zip archive)- Returns:
- an InputStream ready to be read
- Throws:
IOException- if the URL is malformed or the connection could not be opened
-
runWithTimeout
public static <T> T runWithTimeout(Callable<T> task, long timeoutSeconds, String description) throws IOException Runstaskon a bounded background (daemon) thread, guarding against blocking I/O - typically remote N5/Zarr discovery, that can otherwise hang indefinitely on a stalled connection with no feedback to the user.Unlike
openRemoteStream(String)(a single bounded connection), this bounds the *entire* operation, however many network round-trips it internally makes.On timeout, the background thread is best-effort interrupted via
ExecutorService.shutdownNow(); if the underlying I/O call ignores interruption (common for plain socket reads), that thread may still leak until the stalled connection itself eventually times out or errors, but the calling thread is freed immediately to report the failure, rather than hanging alongside it.- Parameters:
task- the (typically network-bound) operation to runtimeoutSeconds- how long to wait before giving updescription- short, human-readable description oftask(e.g. "resolving remote N5/Zarr container"), used in the timeout message- Returns:
- the result of
task - Throws:
RuntimeException- iftaskitself throws one (rethrown as-is, preserving normal control-flow for callers that distinguish specific unchecked exceptions)IOException- iftasktimes out, is interrupted, or throws a checked exception
-
submitBackground
Submitstaskto a bounded background (daemon) thread and returns immediately with a handle to it, instead of waiting for it likerunWithTimeout(java.util.concurrent.Callable<T>, long, java.lang.String)does. Use this when a caller needs to wait on the same operation more than once - e.g. a retry-prompt loop with a growing timeout budget - without restarting the operation from scratch on every attempt, which is what looping calls torunWithTimeout(java.util.concurrent.Callable<T>, long, java.lang.String)would do: each call submits a fresh task to a fresh executor and best-effort cancels it as soon as that call's own wait times out.- Parameters:
task- the (typically network-bound) operation to runthreadName- name given to the backing daemon thread, for diagnostics- Returns:
- a handle bundling the running
Futureand theExecutorServicebacking it; callSNTUtils.BackgroundTask.cancel()exactly once done with it, whether or not it ever completed
-
downloadToTempFile
Downloads a file from the specified URL to a temporary file- Parameters:
fileUrl- the URL of the file to download- Returns:
- the downloaded file
- Throws:
IOException- if an I/O error occursURISyntaxException- if the URL is malformed
-
downloadAndExtractZip
Downloads a zip archive from the specified URL and extracts it to a fresh temporary directory. Both the downloaded archive and the extracted contents are marked for deletion on JVM exit; the archive itself is also deleted immediately once extraction succeeds, since it is not needed afterward.- Parameters:
zipUrl- the URL of the zip archive to download and extract- Returns:
- the temporary directory holding the extracted contents
- Throws:
IOException- if the archive could not be downloaded/read, or if it contains an entry that would extract outside the target directory ("zip-slip")URISyntaxException- if the URL is malformed
-
getContext
public static org.scijava.Context getContext()Convenience method to access the context of the running Fiji instance- Returns:
- the context of the active ImageJ instance. Never null
-
isContextSet
public static boolean isContextSet() -
isStandaloneContext
public static boolean isStandaloneContext()Returns whether the current context was self-initialized by SNT (i.e., no host application like ImageJ/Fiji provided one). This is useful for determining if it is safe to modify global UI state such as the Look and Feel.- Returns:
- true if the context was created by SNT itself, false if provided externally
-
setContext
public static void setContext(org.scijava.Context context) -
startApp
Convenience method to start up SNT's GUI in 'standard' mode.- Returns:
- a reference to the
SNTinstance just started.s
-
startApp
Convenience method to start up SNT's GUI.- Parameters:
streamMode- IftrueSNT is initialized in stream (big data) mode, otherwise in 'standard' mode.- Returns:
- a reference to the
SNTinstance just started.s
-
getInstance()instead