Some libraries with utility classes.
library | description | exported module |
---|---|---|
utility | general purpose utilities | com.dua3.utility |
utility-db | database utilities | com.dua3.utility.db |
utility-fx | JavaFX utilities | com.dua3.utility.fx |
utility-logging | logging utilities and simple logging implementation | com.dua3.utility.logging |
utility-samples | samples | com.dua3.utility.samples |
utility-swing | swing utilities | com.dua3.utility.swing |
This library is developed by Axel Howind and available under the MIT License. Refer to the accompanying file LICENSE for details.
Source code is available at https://github.com/xzel23/utility.
- JDK 17 or later
Binaries are available on Maven Central Repository.
Replace ${utility_version}
with the current version.
<dependency>
<groupId>com.dua3.utility</groupId>
<artifactId>utility</artifactId>
<version>${utility_version}</version>
</dependency>
<dependency>
<groupId>com.dua3.utility</groupId>
<artifactId>utility-db</artifactId>
<version>${utility_version}</version>
</dependency>
...
Replace ${utility_version}
with the current version.
dependencies {
compile "com.dua3.utility:utility:${utility_version}"
compile "com.dua3.utility:utility-db:${utility_version}"
...
}
As of version 12.0.0, logging changed from SLF4J to Log4J-API!
You can use whatever logging implementation you want, for configuration refer to the Log4J documentation. You can also look at the swing samples that use a SwingLogPane and route all logging output regardless of source (Log4J, SLF4J, JUL) to the logging implementation.
This project adds a small lightweight implementation that can be used instead of SLF4J SimpleLogger. It is intended as a lightweight logging implementation in desktop applications or during development and does not support advanced features such as log rotation or writing to a database.
Configuration is done by providing a file called logging.properties
on the classpath.
-
configure log level:
logger.level = (ERROR|WARN|INFO|DEBUG|TRACE)(, <prefix>:(ERROR|WARN|INFO|DEBUG|TRACE))*
setting ony the global level:
logger.level = INFO
setting global level and different levels for packages:
logger.level = WARN, com.dua3.:DEBUG, my.current.project.:TRACE
-
configure logging to console
logger.console.stream = system.out|system.err logger.console.colored = true|false
-
configure a log buffer (see below):
logger.buffer = #entries
Just to save time searching the internet for this:
-
JUL (java.util.logging)
-
add "org.slf4j:jul-to-slf4j:" to your dependencies
-
when using JPMS modules, add
requires jul.to.slf4j;
to your module-info.java -
initialize the bridge handler:
static { java.util.logging.LogManager.getLogManager().reset(); SLF4JBridgeHandler.install(); }
-
-
Log4J2
- add "org.apache.logging.log4j:log4j-to-slf4j:2.18.0" to your dependencies
If you want to show logs in a swing application, configure a log buffer and add a SwingLogPane to your UI. Have a look
at the code of SwingComponentsSample
for details.
Add this to your build.gradle
to include a build.properties
file in your JAR:
// === generate BuildInfo ===
def generateBuildInfo = tasks.register('generateBuildInfo') {
// do not cache the buildinfo
outputs.upToDateWhen { false }
// create build.properties
doLast {
def resourcesDir = sourceSets.main.output.resourcesDir
resourcesDir.mkdirs()
def buildTime = OffsetDateTime.now().atZoneSameInstant(ZoneId.of("UTC"))
def contents = "build.time=${buildTime}\nbuild.version=${version}\n"
def file = new File(resourcesDir, "build.properties")
file.text = contents
}
}
Add this in your code to read the build.properties
file and create a BuildInfo
instance containing version and build
time information:
public static final BuildInfo BUILD_INFO = BuildInfo.create(Main.class, "/build.properties");
Starting with version 14, utility uses JSpecify annotations for all method parameters.
The resulting Jar files are instrumented using Cabe.
When you run your code with assertions disabled, virtually no overhead is introduced, as assertions are removed at JVM level.
When running your code with exceptions enabled, parameters are checked for invalid null values and an AssertionError
will be generated when null is passed for a @NonNull
annotated parameter. The assertion message contains the name of
the parameter.
- all internal logging is done through log4j-api
- org.jspecify annotations are used in the code base; all modules annotated with
@NullMarked
. That you may not passnull
in any method or constructor parameter that is not explicitly annotated as@Nullable
. - module definitions have been reviewed.
- change type parameter for IoUtil.closeAll() to
? extends AutoCloseable
- complete Javadoc
- code cleanup
- IoUtil.closeAll()
- code cleanup
- prevent serialization of logging related classes for security reasons
- javadoc
- FIX: do not throw an exception when temp directory permissions cannot be set, log a warning message instead. The
reason is that especially the Files.setWriteable() does not seem to always return correct results, even when the
directory does have the requested permissions.
- BREAKING: in the fx module, the methods Validator.matches() and Validator.notEmpty() have been renamed to setRegex() and disallowEmpty() to better express the fact that the content is not checked immediately but instead a rule is added that is validated at validation time
- IMPORTANT: resolved ambiguity of LangUtil.ConsumerThrows.andThen() overloads by renaming the version taking an argument of ConsumerThrows to andThenTry(); this might require a source change but code compiled using the previous version should still work in the same way
- IoUtil: added methods createSecureTempDirectory(), createSecureTempDirectoryAndDeleteOnExit(), deleteRecursiveOnExit()
- small improvements and code cleanup
- add overload of DataUtil.diff() that takes a map factory
- TextUtil.toString(Object obj, String valueIfNull)
- use HexFormat for converting Color instances to hex format
- add Text Filter to FxLogPane
- new utility-fx modules with JavaFX related classes and components
- StreamUtil.zip() has been changed to take an operation as third parameter that defines the combining operation
- StreamUtil.concat() did not close streams
- SwingImageUtil, SwingFontUtil have been renamed to AwtImageUtil, AwtFontUtil as they are usable also in non-Swing applications
- Color methods have been renamed to reduce ambiguity
- SwingUtil.getDisplayScale() to retrieve the actual scaling factor for the display (taking into account UHD and retina displays)
- AffineTransformation2f.combine()
- return value of getTextDimension() changed to Rectangle2f (this gives access to the baseline value)
- Rectangle2f.getXCenter(), getYCenter(), min(), max(), center(), dimension(), withCenter()
- Dimension2f.scaled()
- Font.scaled()
- TextUtil.isBlank(CharSequence)
- toolkit agnostic Graphics interface and implementations for Swing and JavaFX
- code cleanups and reorganizations
- Javadoc additions
- many small fixes and improvements
- added i18n package
- ConsoleHandler (utility-logging): make colored output configurable at runtime
- added getGlobalDispatcher to the LogUtilLog4J and LogUtilSLF4J classes
- improve logging performance
- add LogUtilLog4J.init(LogLevel) to initialize the logging system and reroute all logging through Log4J
- log filtering
- extracted common code from the two Swing Logging samples
- added documentation to the LogUtil classes about rerouting logging implementations
- code cleanup and minor fixes
- StopWatch.log...() returns an Object that does the formatting in the toString() method instead of a Supplier to integrate better with logging frameworks (this way, lambda support is not needed)
- TextUtil.nonEmptyOr()
- add LangUtil.require...() overloads for double and float arguments
- LangUtil.isBetween() will throw IllegalArgumentsException when an invalid intervall is specified instead of using an assertion
- support for options that prevent validation when present, i.e., to pass a help flag without the parser throwing an exception when there are problems with other options
- moved to Arguments and made public argument validation methods
- add separate desciption for arguments
- added LangUtil.require...() methods to check integer arguments
- added LangUtil.formatLazy()
- fix: LoggerFactorySlf4j should not dispose the default handler
- add LogEntryDispatcher.getHandlers()
- make Stopwatch(Supplier name) protected
- IoUtil.toURI(Path) returns relative URI when called with relative Path instance
- code cleanup and refactorings
- fix a malformed logging message
- set modification date for zip entries
- fix creation of extra empty file in zip
- add TextUtil.digest() methods to support other digests than MD5
- digests can be calculated on streams without loading the full data into memory
- add IoUtil.zip() and unzip() methods
- javadoc additions
- allow null attr parameter for SwingDocumentFilter methods replace() and insertString()
- javadoc updates
- refactorings and small fixes
- fix race condition in SwingLogPane
- update dependencies and plugins
- code refactorings and small fixes
- remove obsolete null-checks
- update gradle, cabe
- TextUtil.quote(), TextUtil.quoteIfNeeded(), TextUtil.joinQuoted()
- use Java compatible quoting in Arguments.toString()
- add Arguments.toString()
- add Option.toString()
- fix: TextUtil.toSystemLineEnds() appended a newline character even if the argument did not end with newline
- fix: ArgumentsParserTest failed on Windows
- fix runtime error (cabe)
- fix record equals() not accepting null arguments
- make output of ArgumentsParser.help() more compact
- Use assertions to check parameters of internal methods, throw NPE for parameters to methods that are part of the public API. From now on, snapshots and beta versions will unconditionally throw AssertionErrors when null is passed to a parameter that isn't nullable. In release versions, standard assertions are used for internal methods while methods that are part of the public API will throw NullPointerExceptions.
- remove obsolete classes in utility.math.geometry
- fix locale dependent output of toString() implementations
- code cleanup
- dependency updates
- BREAKING: ArgumentsParser has been split into ArgumentsParserBuilder and ArgumentsParser; see unit tests for examples
- BREAKING: RichText.trim() now works the same as String.trim(), i.e. only considers character codes less than or equal to ' ' as whitespace. Use RichText.strip() to remove all whitespace.
- BREAKING: OpenMode.includes() has been renamed to isIncluded()
- BREAKING: removed Pair.toMap() static methods. Use Map.ofEntries() instead.
- BREAKING: LineOutputStream returns lines with line end characters removed
- BREAKING: removed PredefinedDateFormat - use PredefinedDateTimeFormat instead
- Pair<T1,T2> now implements Map.Entry<T1,T2>
- added RichText.strip(), RichText.stripLeading(), RichText.stripTrailing()
- added ThreadFactoryBuilder class
- enable automatic download of Gradle JVM toolchains in build
- util-logging: reworked util-logging, simplified SwingLogPane use, fixed multithreading issues in SwingLogPane
- util-db: added NamedParameterStatement.setInstant(), cleaned up NamedParameterStatement javadoc
- SimpleNamespaceContext: added methods get Prefixes(), getNamespaceURIs
- TextUtil.transform(): accept Object instances as substitutions (String.valueOf() is used for formatting of instances)
- reduce code duplication
- increase unit test coverage
- add @Nullable annotations for record types where needed (because cabe 2.x adds support for record types)
- add javadoc
- fix RichText.split() with non-trivial regex and limit 0 not skipping trailing empty segments in result
- fix build issues on windows
- fix issues in FontDef CSS conversion
- fix font size not extracted when getting FontDef directly from TextAttributes
- fix Vector2f returning NaN for zero denominator
- fix IoUtil.glob() and IoUtil.findFiles() returning paths with inconsistent root under certain circumstances
- fix smaller issues
- update plugins and dependencies
- update log4j to 2.21.0 (according to release notes now fully JLink compatible)
- update plugins and dependencies
- Pair.mapFirst() and Pair.mapSecond()
- code cleanups
- overload TextUtil.getMD5String(byte[])
- Value interface as an abstraction for observable values that is meant to be used in place of JavaFX ObservableValue or Swing Properties in library code that is supposed not to have dependencies on either JavaFX or java.desktop
- (BREAKING) remove deprecations
- (BREAKING) remove LangUtil.checkIndex()
- (BREAKING) reverse order of arguments in CryptUtil.encrypt()/decrypt() with string arguments to match those of byte[] arguments
- lots of Javadoc updates and additions
- add ComboBoxEx
- add ArgumentsDialog
- add SwingDocumentFilter
- add samples project
- reduce code duplication in RichTextBuilder
- exception handling in drag and drop support
- DbUtil.stream()
- make FontDef Cloneable
- RichText.equalizer() returns a customizable equalizer for comparing texts ignoring certain properties
- RichText.wrap() combines styles instead of replacing them
- IOUtil.glob() and IOUtil.listFiles() to search directory trees
- add FileInput drag&drop support to FileInput
- add Qodana to CI pipeline
- code cleanups
- added LangUtil.asFunction()
- Fix XmlUtil.prettyPrint(String) indentation
- Fix XmlUtil.prettyPrint(String) not indenting
- StreamUtil.stream() to create streams from iterators and iterables
- IoUtil.prettyPrint(String) support namespaces; attributes written in alphabetical order
- IoUtil.prettyPrint(String) retains comments in output
- code and javadoc cleanup
- reimplemented XmlUtil.prettyPrint(String) with a StAX parser so that no DOM has to be created when pretty-printing
- DataUtil.convert converting to/from URI, URL, Path, File
- FileInput swing component
- support value "auto" for configuring colored log output. colors are enabled if a terminal is attached and the TERM environment variable is set. this is the new default for this option.
- update plugins, junit
- add overloads for XmlUtil.prettyPrint()
- update gradle, dependencies
- update plugins
- fix compile time warnings in build script
- add XmlUtil.prettyPrint(String)
- use ProgressView.update(PROGRESS_INDETERMINATE) to set indeterminate state
- add assertion messages
- code cleanup
- update dependencies
- fix javadoc problems
- make Option fields private
- FileType.read(): add overloads taking options
- fix AssertionError when writing null value in CSV
- fix handling of default namespace URI in SimpleNamespaceContext
- use version catalog defined in settings.gradle.kts for dependencies and plugins
- update SLF4J to 2.0.1
- add SimpleNamespaceContext for use with XPath
- add XmlUtil.xpath(node) to create namespace aware XPath instances (namespace information is automatically extracted from the node and its parents)
- fix SLF4J warnings on console when running unit tests
- small fixes and improvements
- make XMLUtil namespace aware by default
- log levels can be configured by prefix in logging.properties file
- print exception stack traces in log
- some fixes for SwingProgressView
- Logging is done through SLF4J
- moved the logging stuff to its own library utility-logging so that you don't need to pull everything unless needed
- Java 17 required!
- use Kotlin DSL in gradle build scripts
- changed module names to com.dua3.utility again
- upgraded gradle to 7.4 for Java 17 support
- publish snapshots to sonatype snapshot repository
- geometry classes taking float parameters have been renamed to ...2f
- some classes (Pair, Vector2f, ...) have been converted to records
- updates to FileTreeNode to allow use as a base class
- added BuildInfo class
- add constants for different line ending sequences in TextUtil
- add command line option "--log-path-pattern" to LogUtil
- fix duplicate item output in LangUtil.surroundingItems() when regions overlap
- added several Font.withXXX()-methods to help quickly deriving fonts that differ only in one attribute
- LangUtil.enumValues()
- options can be passed a handler that is executed when arguments.handle() is called
- LangUtil.formatStackTrace(Exception)
- IOUtil.stringStream(String)
- LangUtil.map(OptionalXXX, XXXFunction) for mapping primitive Optionals
- improve output and performance of XmlUtil.prettyPrint()
- fix MathUtil.gcd for negative arguments
- many fixes and smaller improvements, added many Javadoc comments, improve test coverage
- XmlUtil defaultInstance() is now unsynchronized and should be faster
- added LangUtil.orElse() and LangUtil.orElseGet() for Optional-like functionality without creating an Optional instance first
- added cabe annotations to parameters
- rename
IOUtil
,IOOptions
toIoUtil
,IoOptions
- reorder parameters to the different LogAdapter
addListener()
andremoveListener()
methods and add overloads for these methods that add/remove listeners to /from the framework's root logger. - remove LogUtil.format() as it is not shorter than the equivalent lambda (i.e.
LogUtil.format("message %s", arg)
can be replaced by() -> "message %s".formatted(arg)
) - remove MathUtil.toDecimalString()
- remove SandboxURLHandler
- remove methods taking java.io.File; use Path instead
- Color is now an interface with implementations RGBColor and HSVColor
- RichText and Run classes provide an overloaded equals() method that accepts a predicate to give fine-grained control to exclude certain attributes from equality checks
- Platform: added methods to help with quoting arguments for ProcessBuilder
- LangUtil.defaultToString()
- rename RichText.textEquals() to equalsText()
- add equalsTextAndFont(), equalsIgnoreCase()
- add TextUTil.normalizeLineEnds(), TextUtil.toUnixLineEnds(), TextUtil.toWindowsLineEnds(), TextUtil.toSystemLineEnds()
- fix unit test failures on Windows
- StreamUtil.concat()
- StreamUtil.merge()
- Bearer interface
- LangUtil.triStateSelect()
- added FontDef.fontspec()
- small fixes and improvements
The following functionality has been removed because it is available in JDK 17:
- TextUtil.byteArrayToHexString(): use HexFormat.of().formatHex()
- TextUtil.hexStringToByteArray(): use HexFormat.of().parseHex()
- fix AIOOBE in SwingLogPane when messages come in at a high rate
- BACKPORT: StreamUtil.merge()
- add HtmlConverter.inlineTextDecorations()
- some JavaDoc corrections and completions
- update Gradle to 7.2-rc2 for JDK 17 compatibility (during compilation)
- migrate from bintray to sonatype
- JDK 11+ required! It's finally time to dump Java 8 support. I won't put any more effort into supporting a Java version that has long reached EOL and is a maintenance burden because of its missing modularity support.
- build uses Gradle 7 to enable building on JDK 17
- removed use of the JPMS Gradle plugin as it is not compatible with Gradle 7 and not needed anymore after dropping JDK 8 support and Gradle 7 added modularity support.
- logback support has been replaced by log4j2 due to missing jigsaw support in logback. This means if you have been using a Log4J to Logback bridge before, it's now time to do it the other way around.
- NamedParameterStatement supports many more data types; fixes for inserting null values.
- source parameter of CsvReader changed from String to URI
com.dua3.utility.cmd
andcom.dua3.utility.options
have been merged; there had been a lot of duplicated functionality, and the implementation in thecmd
package was much cleaner; the result is again located incom.dua3.utility.options
but the code is mostly based on what had been in thecmd
package. Classes have been renamed because they are no more intended to be used only for command line arguments.- move from JFrog Bintray to Sonatype OSSRH
- ImageUtil.load() does not return Optional
- made Image an interface
- removed the Image.write() method
- added Image.getArgb()
- some changes and fixes to AffineTransformation
- introduce class Dimension2d
- changes to FontUtil interface; rename FontUtil.getTextBounds() to getTextDimension(); loadFont replaced by loadFonts()
- introduce math.geometry package and contained classes
- remove bintray support
- publish builds to GitLab Packages (private access)
- TODO: publish to Mavencentral
- fix: FontDef.merge() only worked if color was set
- add double overload to MathUtil.clamp()
- fix typo: ProgressTracker.State.SCHEDULED (low possibility of breaking client code)
- (Swing): remove MigLayout from runtime dependencies
- (Swing): make SwingProgressView horizontally resizable
- (Swing): fix resize behaviour of SwingLogPane
- RichText.stylesAt()
- RichText.runAt()
- RichText.runs()
- RichText.valueOf() with styles parameter
- LangUtil.surroundingItems()
- CmdParser.errorMessage()
- command line parser improvements & bugfixes
- fix XmlUtil.parse(String)
- add XmlUtil.parse(URI)
- non-throwing (at least when correctly configured, otherwise RTE), reusable XmlUtil.defaultInstance()
- remove the Text class
- some changes in XmlUtil
- XmlUtil.xpath()
- change argument of XmlUtil.format() from Document to its superclass Node
- DomUtil renamed to XmlUtil, methods are instance methods now so that instances using different DocumentBuilder and Transformer implementations can be used
- moved all XML related methods from IoUtil and TextUtil to XmlUtil
- SwingUtil: added helper methods for adding basic drag and drop support
- IOUtil: added IOUtil.copyAllBytes()
- IOUtil: removed inaccessible Method StreamSupplier.lines()
- NamedParameterStatement: don't throw exception in constructor if parameter info can not be queried; fix typo in method name
- NamedParameterStatement: support null values
- RichText performance improvements
- FIX: possible negative index in SwingLogPane
- javadoc
- remove a stray unused interface
- FIX: do not generate interleaved tags in HtmlConverter
- added missing javadoc in many places
- removed obsolete classes and methods (those should have been in use anyway and can in any case be easily replaced with the newer versions/replacements)
- small fixes and cleanups
- moved/renamed command line argument parsing classes to their own package, many changes and additions
- move Font.FontDef to upper level
- RichTextBuilder: methods push(Style)/pop(Style), implement Comparable; add textEquals(); bugfixes
- Many RichText/TextAttributes/Style related refactorings
- new classes HtmlConverter, StyledDocumentConverter, AnsiConverter to convert RichText to different formats
- removed old StyledDocumentBuilder class
- several changes in to the classes under util.text
- removed ToStringBuilder class as it was never really used and most IDEs can generate toString() automatically
- overload IOUtil.replaceExtension for Path
- DataUtil.asFunction() to use Map instances as Function
- TextUtil.appendHtmlEscapedCharacters(); mm2pt(); pt2mm()
- update SpotBugs and remove rule filter
- logging: removing log listeners from JUL/Logback/System.out
- classes SwingLogPane and LogBuffer
- RingBuffer implements the Collection interface
- RingBuffer.subList()
- release to solve problems with build - no code changes
- FIX: should be "font-size", not "size"
- fix spelling of TextUtil.getTextBounds()
- remove deprecated Font.isUnderlined()
- FIX: Color.isOpaque() returned wrong value
- FIX: Font.getCssStyle(): returned invalid value "regular" instead of "normal" for font-style
- Color.isTransparent()
- more work on command line parser
- added simple command line parser class
- promote ProgressTracker from incubator to concurrent package
- SwingProcessView: more informative exception messages
- Font: fix fontspec parsing
- Font: fix fontspec parsing when font size does not contain a fractional part; do not output fractional part in fontspec if unneeded
- fontspec color part changed to CSS format (might break app that rely on the fontspec format)
- new constructor Font(String fontspec)
- Font valueOf(String) expects arg in CSS format (might be breaking)
- Color: new methods isOpaque(), toRgba(), toArgb(), toCss()
- mark Font.FontDef final
- cache Font.fontspec
- Font.similar()
- fix invalid CSS for Fontdef if underline or strikethrough is set explicitly to false
- fix exception and debug messages using default locale instead if Locale.ROOT
- interface ProgressTracker, incubating class SwingProgressView
- fix IOUtil.replaceExtension(), IOUtil.stripExtension() when path contains multiple dots
- IOUtil.lines(InputStream, Charset)
- always use "\r\n" as line delimiter in CSV files (as per RFC 4180)
- minor improvements and code cleanups
- change Font.isUnderlined() to isUnderline()
- new Utility class StreamUtil
- TextUtil.indent()
- DomUtil and BatchCollector moved out of incubator
- new method FontDef.getCssStyle() returning CSS-compatible font definition
- new method IOUtil.openStream(URI)
- new overload IOUtil.read(URI, Charset)
- now included in Maven Central Repository
- add instructions for setting up Maven
- fix instructions for setting up Gradle
- many code cleanups
- test code compatible with JDK 8 (but JDK 11+ is still required for the build)
- utility method TextUtil.prettyPrint(...) for pretty-printing org.w3c.dom.Document
- utility methods IOUtil.format(...) for output of org.w3c.dom.Document
- Font.FontDef: added equals(), hashCode(), toString()
- added new package com.dua3.utility.incubator for incubating features
- new Utility class DomUtil (incubating)
- new class BatchCollector (incubating)
- fix missing root in getUnixPath()
- support Path as argument to FileType.read()/write() methods
- new method FileType.isCompound() is used to exclude file types from lookup by extension (default implementation returns false; see javadoc for details)
- LangUtil.uncheckedXXX() methods don't wrap uncheckedExceptions
- relaxed some method parameters from String to CharSequence
- code cleanup
- improve unit test coverage
- Java 8 compatibility fixes: remove usage of API not available in Java 8
- restore Java 8 compatibility (needed for my customer's project)
- update gradle to 6.3 (for JDK 14 support)
- update SpotBugs and SpotBugs plugin
- Pair.of(Map.Entry)
- add split support to stopwatch class
- IOUtil.toUnixPath()
- TextUtil.containsAnyOf()
- TextUtil.containsNoneOf()
- IOUtil.toUri()
- IOUtil.toPath()
- Removal of utility-json
- TextUtil.transform(String, Pair<String,String>...)
- added methods in LangUtil to resolve localized resources
- minor cleanups
- Methods in IOUtil that take a filename as a String argument have been changed to return correct results when instead of a filename a path is given.
- add Zip class
- add TextUtil.generateMailToLink()
- update to gradle 6.0.1
- add Platform class
- update to gradle 6.0; fix gradle 7 compatibility warnings
- fix DataUtil.convert() to LocalDateTime conversion
- added some unit tests
- Option.fileOption(): added OpenMode
- code cleanup
- LangUtil.enumSet()
- Update spotbugs to 4.0.0-beta4 to be able to compile using JDK 13.
DataUtil.convert()
: be more strict with boolean conversions. Converting aString s
toBoolean
will yieldnull
ifs
isnull
,Boolean.TRUE
if and only ifs
equals ignoring case"true"
,Boolean.FALSE
if and only ifs
equals ignoring case"false"
. In all other casesIllegalArgumentException
is thrown.
- fixed many small issues, typos (also in method names), so that I decided to also bump the major version
- module names changed to dua3_util*
DataUtil.convert()
overload for converting collections to listDataUtil.convertCollection()
for converting collections to collection of arbitrary type- (4.1.0-BETA12a): fix for
DataUtil.convert()
- don't bail out early if source type isDouble
orFloat
LangUtil.uncheckedSupplier()
- new:
ÌOUtil.getInputStream(Object)
andÌOUtil.getOutputStream(Object)
- new:
MathUtil.roundingOperation(int n, RoundingMode mode)
for bulk rounding, with support for all types ofjava.math.RoundingMode
- Better documentation for
MathUtil.round()
andMathUtil.roundToPrecision()
- fixed some compilation warnings
DataUtil.collect()
andDataUtil.collectArray()
- LangUtil:
public static <E extends Exception> void check(boolean condition, Supplier<E> exceptionSupplier) throws E
- new class
MappingIterator
and methodDataUtil.map(Iterator<T>, Function<T,U>)
- new class
FilterIterator
and methodDataUtil.filter(Iterator<T>, Predicate<T>)
- Support converting Long, Integer to Double, Float in DataUtil.convert...()-methods
- Support converting String to LocalDate in the DataUtil.convert...()-methods
DataUtil.convert()
andDataUtil.convertToArray()
for converting objects to other types. Conversion is done as follows:- if value is {@code null}, {@code null} is returned;
- if the target class is assignment compatible, a simple cast is performed;
- if the target class is
String
,Object.toString()
is used; - if the target class is an integer type and the value is of type double, a conversion without loss of precision is tried;
- if the target class provides a method
public static T valueOf(T)
andvalue instanceof U
, that method is invoked; - if
useConstructor
istrue
and the target class provides a constructor taking a single argument of value's type, that constructor is used; - otherwise an exception is thrown.
- new class
DataUtil
, methods for data conversion
- new helper method
TextUtil.align()
- BREAKING: default separator for CSV changed from semicolon to comma to make it compliant with RFCc4180. To change
the separator, use
CsvIo.getOptionValues(CsvIo.OPTION_SEPARATOR, ';')
when creating theCsvReader
/CsvWriter
instance.
- FileType: new static
read(path, class)
method
- IOUtil: add more conversion methods between URI, URL, and Path
- remove version file
- update spotbugs plugin
- cleanup build file
- IOUtil.getFileExtension(URI)
- new class
JsonUtil
: loading JSON from URL/path
JdbcDataSource.setUser()
andJdbcDataSource.setPassword()
supportnull
argument to unset value.
- Change default date format to use a 4-digit year.
- utility-json.
BETA 4
- changed the build system to make life easier for me as developer :) - version information is stored in a file
named
version
in the project root. This makes it possible to consistently update dependencies information automatically using a script.
BETA 3
- set dependency version information in gradle.properties file
- JdbcDriverInfo: create connection URL from option values
BETA 2
- don't use decimal grouping in CSV output
ValueChangeListener
support inOptionValues
- classes
FileType
andOpenMode
- fix CSV date formatting issues
BETA 1
- update gradle wrapper
CsvReader
andCsvWriter
classes- new classes
Option
(an option to control object behavior),OptionSet
(a set of options to control object behavior), andOptions
(a set of options and corresponding values) - new package
com.dua3.utility.data
with classesTreeNode
(to build tree data structures) andFileTreeNode
to create a tree of files and subdirectories of a directory - moved the
Pair
andColor
classes to thecom.dua3.utility.data
package - renamed
Options
toOptionValues
- add
uses
declarations inmodule-info.java
files (fix ServiceLoader issues when run from eclipse) - spotbugs: use exclude filter for false positives; don't ignore failures
- Added methods to measure text in TextUtil. The concrete implementation is using either AWT or JavaFX and is loaded via a ServiceLoader. The AWT implementation is included in utility.swing whereas a JavaFX implementation is included in the fx.util subproject of the fx project.
- skipped
- Fix NamedParameterStatement throwing exception when using ojdbc8.jar with certain statements.
- The git repository moved to https://gitlab.com/com.dua3/lib/utility.git
- Added
NamedParameterStatement.getParameterInfo()
andNamedParameterStatement.getParameterInfo(String)
to query parameter meta data (i.e. the corresponding SQL type) - Added
NamedParameterStatement.getResultSet()
- Added
NamedParameterStatement.getUpdateCount()
- Added
DbUtil.toLocalTime()
- changed license to MIT to make it possible to use in pre-V3 GPL projects
- BREAKING: package
com.dua3.utility.db
was moved to a separate libraryutility.db
. You have to update dependencies and module-info. - REMOVED:
Font.getAwtFont()
andFont.getTextWidth()
; these introduced a dependency on java.desktop and can be easily replaced where needed. - The utility.db library now include methods to dynamically load JDBC drivers. This allows to use jlink on applications that use non-modular JDBC-drivers.
- dependencies on these modules were removed from the main library, allowing for smaller
jlink
images:- java.xml
- java.desktop
- java.sql
- New class CryptUtil: encryption and decryption utility.
- TextUtil.base64Encode()
- TextUtil.base64Decode()
- breaking change: TextUtil.byteArrayToHex() has been renamed to byteArrayToHexString()
- TextUtil.hexStringToByteArrayToHex()
- IOUtil.loadText(): helper method to load text files where the character encoding is not known.
- Requires Java 11+
- Removed Swing and JavaFX.