Package sc.fiji.snt

Class SNTUtils

java.lang.Object
sc.fiji.snt.SNTUtils

public class SNTUtils extends Object
Static utilities for SNT
  • Field Details

  • Method Details

    • getReadableVersion

      public static String getReadableVersion()
    • addViewer

      public static void addViewer(Viewer3D viewer)
    • removeViewer

      public static void removeViewer(Viewer3D viewer)
    • getViewers

      protected static HashMap<Integer,Viewer3D> getViewers()
    • error

      public static void error(String string)
    • error

      public static void error(String string, boolean queueNotice)
      As error(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 message
      queueNotice - whether to also mirror the message into the notification-center queue
    • setPlugin

      protected static void setPlugin(SNT plugin)
    • getPluginInstance

      @Deprecated public static SNT getPluginInstance()
      Deprecated.
      use getInstance() instead
    • getInstance

      public static SNT getInstance()
    • error

      public static void error(String string, Throwable t)
    • error

      public static void error(String string, Throwable t, boolean queueNotice)
      As error(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 message
      t - the associated exception, or null
      queueNotice - whether to also mirror the message into the notification-center queue
    • log

      public static void log(String string)
    • warn

      public static void warn(String string)
    • csvQuoteAndPrint

      public static void csvQuoteAndPrint(PrintWriter pw, Object o)
    • stripExtension

      public static String stripExtension(String filename)
    • sanitizeFilename

      public static String sanitizeFilename(String filename)
      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 filename is null
    • getLastElement

      public static String getLastElement(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". 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 filePathOrUrlOrCloudLink is null or blank
    • getCacheDir

      public static File getCacheDir()
      Returns SNT's own scratch/cache directory, used by disk-backed operations (e.g. DiskBackedStorageBackend, Lazy). Unlike the workspace directory (see SNTPrefs#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

      public static SNTUtils.HeapInfo getHeapInfo()
      Returns:
      a snapshot of current JVM heap usage
    • formatBytes

      public static String formatBytes(long bytes)
      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 of getCacheDir(). 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

      public static File getUniquelySuffixedTifFile(File referenceFile)
    • getUniquelySuffixedFile

      public static File getUniquelySuffixedFile(File referenceFile)
    • getUniquelySuffixedFile

      public static File getUniquelySuffixedFile(File referenceFile, String forcedExtension)
    • fileAvailable

      public static boolean fileAvailable(File file)
    • isValidURL

      protected static boolean isValidURL(String url)
    • isReachable

      public static boolean isReachable(String url, int timeoutMs)
      Checks for whether url'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 check
      timeoutMs - connect timeout, in milliseconds
      Returns:
      true if the host could be reached (or url is not a plain http(s) URL); false if a connection could not be established within timeoutMs
    • formatDouble

      public static String formatDouble(double value, int digits)
    • getDecimalFormat

      public static DecimalFormat getDecimalFormat(double value, int digits)
    • 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

      public static File findClosestPair(File file, String[] pairExts)
    • findClosestPair

      public static File findClosestPair(File file, String pairExt)
    • getSanitizedUnit

      public static String getSanitizedUnit(String unit)
    • randomPaths

      public static List<Path> randomPaths()
      Generates a list of random paths. Only useful for debugging purposes
      Returns:
      the list of random Paths
    • getElapsedTime

      public static String getElapsedTime(long fromStart)
    • getReconstructionFiles

      public static File[] getReconstructionFiles(File dir, String pattern)
      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 containing pattern will be imported from the directory. null allowed.
      Returns:
      the array of files. An empty list is retrieved if dir is not a valid, readable directory.
    • isReconstructionFile

      public static boolean isReconstructionFile(File file)
    • getBackupCopies

      public static List<File> getBackupCopies(File location, String baseName)
      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 files
      baseName - 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

      public static List<File> getBackupCopies(File location)
      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

      public static LocalDateTime nowTruncatedToSeconds()
      Returns the current date-time truncated to whole seconds, e.g., for stamping exported content with a generation time.
    • getTimeStamp

      public static String getTimeStamp()
    • extractReadableTimeStamp

      public static String extractReadableTimeStamp(File file)
    • 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 every true has been balanced by a matching false, 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 it
      streamMode - true for the wide "SNT Stream" layout, false for the default one
    • openRemoteStream

      public static InputStream openRemoteStream(String url) throws IOException
      Opens an InputStream to url with explicit connect/read timeouts, so a stalled or unreachable remote host fails with a clear IOException instead of hanging indefinitely - the default behavior of URL.openStream(), whose underlying URLConnection has 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 than runWithTimeout(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
      Runs task on 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 run
      timeoutSeconds - how long to wait before giving up
      description - short, human-readable description of task (e.g. "resolving remote N5/Zarr container"), used in the timeout message
      Returns:
      the result of task
      Throws:
      RuntimeException - if task itself throws one (rethrown as-is, preserving normal control-flow for callers that distinguish specific unchecked exceptions)
      IOException - if task times out, is interrupted, or throws a checked exception
    • submitBackground

      public static <T> SNTUtils.BackgroundTask<T> submitBackground(Callable<T> task, String threadName)
      Submits task to a bounded background (daemon) thread and returns immediately with a handle to it, instead of waiting for it like runWithTimeout(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 to runWithTimeout(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 run
      threadName - name given to the backing daemon thread, for diagnostics
      Returns:
      a handle bundling the running Future and the ExecutorService backing it; call SNTUtils.BackgroundTask.cancel() exactly once done with it, whether or not it ever completed
    • downloadToTempFile

      public static File downloadToTempFile(String fileUrl) throws IOException, URISyntaxException
      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 occurs
      URISyntaxException - if the URL is malformed
    • downloadAndExtractZip

      public static File downloadAndExtractZip(String zipUrl) throws IOException, URISyntaxException
      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

      public static SNT startApp()
      Convenience method to start up SNT's GUI in 'standard' mode.
      Returns:
      a reference to the SNT instance just started.s
    • startApp

      public static SNT startApp(boolean streamMode)
      Convenience method to start up SNT's GUI.
      Parameters:
      streamMode - If true SNT is initialized in stream (big data) mode, otherwise in 'standard' mode.
      Returns:
      a reference to the SNT instance just started.s