Class Utilities

java.lang.Object
org.jjazz.utilities.api.Utilities

public class Utilities extends Object
Various convenience functions.
  • Constructor Details

    • Utilities

      public Utilities()
  • Method Details

    • installTimeStampLogging

      public static void installTimeStampLogging(Logger logger)
      Make logging message include a time stamp in milliseconds, relative to the time of the first logged message in the application.

      Note: this will impact other Logging of other modules as well, but if not registered explicitly, class will be displayed as null.

      Parameters:
      logger - The logger for which to apply the new logging message
    • isWindows

      public static boolean isWindows()
    • isMac

      public static boolean isMac()
    • isLinux

      public static boolean isLinux()
    • isStatic

      public static <T> boolean isStatic(Class<T> clazz)
      Check if a class is a static class.
      Type Parameters:
      T -
      Parameters:
      clazz -
      Returns:
    • isInnerClass

      public static <T> boolean isInnerClass(Class<T> clazz)
      Check if a class is an inner class (ie a non-static nested class).
      Type Parameters:
      T -
      Parameters:
      clazz -
      Returns:
    • loadFileFromURL

      public static void loadFileFromURL(Path file, URL url, int secsConnectTimeout, int secsReadTimeout, org.netbeans.api.progress.ProgressHandle ph, int expectedFileSizeKb) throws IOException
      Downloads from a (http/https) URL and saves to a file.

      Parameters:
      file - File to write. Parent directory will be created if necessary
      url - http/https url to connect
      secsConnectTimeout - Seconds to wait for connection establishment
      secsReadTimeout - Read timeout in seconds - trasmission will abort if it freezes more than this
      ph - If not null, starts and updates it while download is progressing using expectedFileSizeKb
      expectedFileSizeKb -
      Throws:
      IOException
    • getFileSize

      public static long getFileSize(URL url) throws IOException
      Get file size from an URL.
      Parameters:
      url -
      Returns:
      File size in bytes, or -1 if file content length is unknown
      Throws:
      IOException
    • getCurrentDir

      public static String getCurrentDir()
      Returns:
      Complete absolute path from where the application was initialized.
    • isEmpty

      public static boolean isEmpty(Path dirPath) throws IOException
      Check if a directory is empty.

      Best performance as the Java 8 Files.list() returns a lazily populated stream (avoid reading all files).

      Parameters:
      dirPath -
      Returns:
      Throws:
      IOException
    • extractHttpURLs

      public static List<URL> extractHttpURLs(String text)
      Extract from text all http://xxx or https://xxx URL strings as URLs.

      Malformed URLs are ignored.

      Parameters:
      text -
      Returns:
    • extractFileURLsAsFiles

      public static List<File> extractFileURLsAsFiles(String text)
      Extract from text all file:/xxx URL strings as Files.

      Malformed URLs are ignored.

      Parameters:
      text -
      Returns:
    • endsWithIgnoreCase

      public static boolean endsWithIgnoreCase(String str, String ext)
      Returns:
      True if str ends with ext, ignoring case.
    • getExtension

      public static String getExtension(String fileName)
      Return the extension (without the ".")
      Parameters:
      fileName -
      Returns:
      Empty string if no dot.
    • replaceExtension

      public static String replaceExtension(String filename, String ext)
      Replace the path extension (the trailing ".something") of filename by ext.

      If filename has no path extension just add ext.

      Parameters:
      filename -
      ext - A string without spaces in it. If ext does not start with "." it will be added. If "" extension is removed.
      Returns:
      The new filename with extension replaced.
    • getSecuredXStreamInstance

      public static com.thoughtworks.xstream.XStream getSecuredXStreamInstance()
      Get a secured XStream instance for unmarshalling which only accepts org.jjazz.** objects.
      Returns:
    • truncateWithDots

      public static String truncateWithDots(Collection<?> collection, int maxLength)
      Get the string of all the collection elements in brackets [], but limited to maxLength.
      Parameters:
      collection -
      maxLength - Must be >= 5
      Returns:
      A string like [one,two,th...] if maxLength is 15
    • truncateWithDots

      public static String truncateWithDots(String s, int maxLength)
      Return a string based on s whose length can't exceed maxLength, with "..." at the end if s was truncated.

      If s length is <= maxSize then return s. Otherwise return the first chars and append ".." or "...", in order to have length=maxSize.

      Example: return "Clav..." for s="Clavinet" and maxLength=7

      Parameters:
      s -
      maxLength - Must be >= 3
      Returns:
    • truncate

      public static String truncate(String s, int max)
      Return the truncated string if s exceeds max chars.
      Parameters:
      s -
      max -
      Returns:
    • heapPermutation

      public static <T> void heapPermutation(T[] smallArray, int n, List<T[]> result)
      Generate all the permutations of the specified smallArray in the result list.

      Type Parameters:
      T -
      Parameters:
      smallArray - Size must be <= 9, otherwise use too much memory (result size grow like N!).
      n - Nb of elements to be considered
      result - The list of all smallArray permutations.
    • toString

      public static String toString(byte[] buf)
    • swapList

      public static <T> void swapList(List<T> l1, List<T> l2)
      Swap the contents of 2 lists.
      Parameters:
      l1 -
      l2 -
    • reverseGet

      public static Object reverseGet(Map<?,?> map, Object v)
      Return the first key of a map for which value = v.
      Parameters:
      map - Map
      v -
      Returns:
      Object Null if found no value=v
    • indexOfInstance

      public static int indexOfInstance(List<?> list, Class<?> clazz)
      Get the list index of the first object which is instance of a specified class.
      Parameters:
      list -
      clazz -
      Returns:
      int -1 if no object is instance of clazz.
    • expand

      public static String expand(String s, int l, String es)
      Return a new string which is a copy of s with as many as required es strings appended to reach length l (or more).

      If s length is more than l nothing is done.

      Parameters:
      s -
      l -
      es -
      Returns:
    • getObjectRefIndex

      public static int getObjectRefIndex(Object o, List<? extends Object> array)
      Get the index of an object reference in a List. The search uses direct equality '==', NOT the 'equals' function.
      Parameters:
      o - The Object to search.
      array - The List of Objects to be searched.
      Returns:
      The index of object o, -1 if not found.
    • indexOfStringIgnoreCase

      public static int indexOfStringIgnoreCase(List<? extends Object> list, String str)
      Return the index of the first object whose toString() function match str (ignoring case).
      Parameters:
      list - A list of object.
      str - The string to search (ignoring case)
      Returns:
      The index of matching string, -1 if not found.
    • extractZipResource

      public static <T> List<File> extractZipResource(Class<T> myClass, String zipResource, Path destDir, boolean overwrite)
      Extract the contents of a .zip resource file to a destination directory.

      Type Parameters:
      T -
      Parameters:
      myClass - The class used to find the zipResource.
      zipResource - Must end with ".zip".
      destDir - The path of the destination directory, which must exist.
      overwrite - If true overwrite files in the destination directory
      Returns:
      The list of created files in the destination directory.
    • copyResource

      public static <T> boolean copyResource(Class<T> c, String resourceFilePath, Path targetFile)
      Copy a resource file to a target file.

      Replace existing target file if already present.

      Type Parameters:
      T -
      Parameters:
      c -
      resourceFilePath - The resource path for class c
      targetFile -
      Returns:
      False if a problem occured
    • fontAsString

      public static String fontAsString(Font font)
      Convert a font into a string that can be decoded by Font.decode()
      Parameters:
      font -
      Returns:
    • toMultilineString

      public static <K, V> String toMultilineString(Map<K,V> map)
      Get each element toString() called, one per line.
      Type Parameters:
      K -
      V -
      Parameters:
      map - If it's a NavigableMap, use its ascending order.
      Returns:
    • toMultilineString

      public static String toMultilineString(Collection<?> list)
      Get each element toString() called, one per line.
      Parameters:
      list -
      Returns:
    • toMultilineString

      public static <T> String toMultilineString(T[] array)
      Get each element toString() called, one per line.
      Parameters:
      array -
      Returns:
    • toDebugString

      public static String toDebugString(PropertyChangeEvent e)
      A debug string for a PropertyChangeEvent.
      Parameters:
      e -
      Returns:
    • getLocation

      public static URL getLocation(Class<?> c)
      Gets the base location of the given class. Manage all OS variations and possible problems in characters...

      If the class is directly on the file system (e.g., "/path/to/my/package/MyClass.class") then it will return the base directory (e.g., "file:/path/to").

      If the class is within a JAR file (e.g., "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the path to the JAR (e.g., "file:/path/to/my-jar.jar").

      Parameters:
      c - The class whose location is desired.
    • urlToFile

      public static File urlToFile(URL url)
      Converts the given URL to its corresponding File.

      This method is similar to calling new File(url.toURI()) except that it also handles "jar:file:" U Sgs, returning the path to the JAR file.

      Parameters:
      url - The URL to convert.
      Returns:
      A file path suitable for use with e.g. FileInputStream
      Throws:
      IllegalArgumentException - if the URL does not correspond to a file.
    • urlToFile

      public static File urlToFile(String url)
      Converts the given URL string to its corresponding File.
      Parameters:
      url - The URL to convert.
      Returns:
      A file path suitable for use with e.g. FileInputStream
      Throws:
      IllegalArgumentException - if the URL does not correspond to a file.
    • loadFileAsString

      public static String loadFileAsString(org.openide.filesystems.FileObject fo)
      Load a file content as a string.
      Parameters:
      fo -
      Returns:
      Null if problem reading file
    • indexOf

      public static int indexOf(byte[] data, byte[] pattern)
      Finds the first occurrence of the pattern in the text.

      Use Knuth-Morris-Pratt Algorithm for Pattern Matching.

      Returns:
      -1 if not found.
    • listFiles

      public static HashSet<Path> listFiles(File dirTree, FilenameFilter fnFilter, String ignoreDirPrefix, int maxDepth)
      Get all the files matching fnFilter in dirTree (and its subdirectories).

      Hidden subdirectories are not searched.

      Parameters:
      dirTree -
      fnFilter - If null accept all files.
      ignoreDirPrefix - Subdirs starting with this prefix are not traversed. If null accept all subdirectories.
      maxDepth -
      Returns:
    • openInBrowser

      public static boolean openInBrowser(URL url, boolean silentError)
      Open an URL in the system's external browser.

      Unless silentError is true, user is notified if an error occured.

      Parameters:
      url -
      silentError - Do not notify user if error occured
      Returns:
      False if an error occured
    • openFile

      public static boolean openFile(File file, boolean silentError)
      Open a file in an external editor.

      Unless silentError is true, user is notified if an error occured.

      Parameters:
      file -
      silentError - Do not notify user if error occured
      Returns:
      False if an error occured
    • browseFileDirectory

      public static boolean browseFileDirectory(File file, boolean silentError)
      Browse in a file browser a folder containing the specified file .

      Unless silentError is true, user is notified if an error occured.

      Parameters:
      file -
      silentError - Do not notify user if error occured
      Returns:
      False if an error occured
    • shutdownAndAwaitTermination

      public static void shutdownAndAwaitTermination(ExecutorService pool, long waitTerminationTimeMs, long waitCancelTimeMs)
      Shutdown an executor service in a clean way.

      From https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ExecutorService.html

      Parameters:
      pool -
      waitTerminationTimeMs - Time in milliseconds to wait for pool tasks to terminate themselves
      waitCancelTimeMs - Time in milliseconds to wait for pool tasks to handle the cancel requests