Class Utilities
-
Nested Class Summary
Nested Classes -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic booleanbrowseFileDirectory(File file, boolean silentError) Browse in a file browser a folder containing the specified file .static <T> booleancopyResource(Class<T> c, String resourceFilePath, Path targetFile) Copy a resource file to a target file.static booleanendsWithIgnoreCase(String str, String ext) static StringReturn a new string which is a copy of s with as many as required es strings appended to reach length l (or more).extractFileURLsAsFiles(String text) Extract from text all file:/xxx URL strings as Files.extractHttpURLs(String text) Extract from text all http://xxx or https://xxx URL strings as URLs.extractZipResource(Class<T> myClass, String zipResource, Path destDir, boolean overwrite) Extract the contents of a .zip resource file to a destination directory.static StringfontAsString(Font font) Convert a font into a string that can be decoded by Font.decode()static Stringstatic StringgetExtension(String fileName) Return the extension (without the ".")static longgetFileSize(URL url) Get file size from an URL.static URLgetLocation(Class<?> c) Gets the base location of the given class.static intgetObjectRefIndex(Object o, List<? extends Object> array) Get the index of an object reference in a List.static com.thoughtworks.xstream.XStreamGet a secured XStream instance for unmarshalling which only accepts org.jjazz.** objects.static <T> voidheapPermutation(T[] smallArray, int n, List<T[]> result) Generate all the permutations of the specified smallArray in the result list.static intindexOf(byte[] data, byte[] pattern) Finds the first occurrence of the pattern in the text.static intindexOfInstance(List<?> list, Class<?> clazz) Get the list index of the first object which is instance of a specified class.static intindexOfStringIgnoreCase(List<? extends Object> list, String str) Return the index of the first object whose toString() function match str (ignoring case).static voidinstallTimeStampLogging(Logger logger) Make logging message include a time stamp in milliseconds, relative to the time of the first logged message in the application.static booleanCheck if a directory is empty.static <T> booleanisInnerClass(Class<T> clazz) Check if a class is an inner class (ie a non-static nested class).static booleanisLinux()static booleanisMac()static <T> booleanCheck if a class is a static class.static booleanlistFiles(File dirTree, FilenameFilter fnFilter, String ignoreDirPrefix, int maxDepth) Get all the files matching fnFilter in dirTree (and its subdirectories).static StringloadFileAsString(org.openide.filesystems.FileObject fo) Load a file content as a string.static voidloadFileFromURL(Path file, URL url, int secsConnectTimeout, int secsReadTimeout, org.netbeans.api.progress.ProgressHandle ph, int expectedFileSizeKb) Downloads from a (http/https) URL and saves to a file.static booleanOpen a file in an external editor.static booleanopenInBrowser(URL url, boolean silentError) Open an URL in the system's external browser.static StringreplaceExtension(String filename, String ext) Replace the path extension (the trailing ".something") of filename by ext.static ObjectreverseGet(Map<?, ?> map, Object v) Return the first key of a map for which value = v.static voidshutdownAndAwaitTermination(ExecutorService pool, long waitTerminationTimeMs, long waitCancelTimeMs) Shutdown an executor service in a clean way.static <T> voidSwap the contents of 2 lists.static StringA debug string for a PropertyChangeEvent.static StringtoMultilineString(Collection<?> list) Get each element toString() called, one per line.static <K,V> String toMultilineString(Map<K, V> map) Get each element toString() called, one per line.static <T> StringtoMultilineString(T[] array) Get each element toString() called, one per line.static StringtoString(byte[] buf) static StringReturn the truncated string if s exceeds max chars.static StringtruncateWithDots(String s, int maxLength) Return a string based on s whose length can't exceed maxLength, with "..." at the end if s was truncated.static StringtruncateWithDots(Collection<?> collection, int maxLength) Get the string of all the collection elements in brackets [], but limited to maxLength.static FileConverts the given URL string to its correspondingFile.static File
-
Constructor Details
-
Utilities
public Utilities()
-
-
Method Details
-
installTimeStampLogging
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
Check if a class is a static class.- Type Parameters:
T-- Parameters:
clazz-- Returns:
-
isInnerClass
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 necessaryurl- http/https url to connectsecsConnectTimeout- Seconds to wait for connection establishmentsecsReadTimeout- Read timeout in seconds - trasmission will abort if it freezes more than thisph- If not null, starts and updates it while download is progressing using expectedFileSizeKbexpectedFileSizeKb-- Throws:
IOException
-
getFileSize
Get file size from an URL.- Parameters:
url-- Returns:
- File size in bytes, or -1 if file content length is unknown
- Throws:
IOException
-
getCurrentDir
- Returns:
- Complete absolute path from where the application was initialized.
-
isEmpty
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
Extract from text all http://xxx or https://xxx URL strings as URLs.Malformed URLs are ignored.
- Parameters:
text-- Returns:
-
extractFileURLsAsFiles
Extract from text all file:/xxx URL strings as Files.Malformed URLs are ignored.
- Parameters:
text-- Returns:
-
endsWithIgnoreCase
- Returns:
- True if str ends with ext, ignoring case.
-
getExtension
Return the extension (without the ".")- Parameters:
fileName-- Returns:
- Empty string if no dot.
-
replaceExtension
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
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
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
Return the truncated string if s exceeds max chars.- Parameters:
s-max-- Returns:
-
heapPermutation
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 consideredresult- The list of all smallArray permutations.
-
toString
-
swapList
Swap the contents of 2 lists.- Parameters:
l1-l2-
-
reverseGet
Return the first key of a map for which value = v.- Parameters:
map- Mapv-- Returns:
- Object Null if found no value=v
-
indexOfInstance
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
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
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
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
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 ctargetFile-- Returns:
- False if a problem occured
-
fontAsString
Convert a font into a string that can be decoded by Font.decode()- Parameters:
font-- Returns:
-
toMultilineString
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
Get each element toString() called, one per line.- Parameters:
list-- Returns:
-
toMultilineString
Get each element toString() called, one per line.- Parameters:
array-- Returns:
-
toDebugString
A debug string for a PropertyChangeEvent.- Parameters:
e-- Returns:
-
getLocation
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
Converts the givenURLto its correspondingFile.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
Converts the given URL string to its correspondingFile.- 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
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
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
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
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 themselveswaitCancelTimeMs- Time in milliseconds to wait for pool tasks to handle the cancel requests
-