Example Use Cases
Below are some example use case snippets from the examples.
/**
* Writes the value of the object to the file.
*
* @param value the value to write, cannot be {@code null}
*
* @throws UncheckedIOException if an error occurs writing the data
*/
public void write(final Object value) {
AppLogger.LOGGER.appVersion("ContentWriter", 1, 0, 0, "Beta1"); (1)
Objects.requireNonNull(value, ErrorMessages.MESSAGES.nullParam("value")); (2)
write(Objects.requireNonNull(value, ErrorMessages.MESSAGES.nullParam("value")).toString());
}
/**
* Writes the value to the file.
*
* @param value the value to write, cannot be {@code null} or an {@linkplain String#isEmpty() empty string}.
*
* @throws UncheckedIOException if an error occurs writing the data
*/
public void write(final String value) {
AppLogger.LOGGER.appVersion("ContentWriter", 1, 0, 0, "Beta1");
if (Objects.requireNonNull(value, ErrorMessages.MESSAGES.nullParam("value")).isEmpty()) {
throw ErrorMessages.MESSAGES.invalidValue(value); (3)
}
try {
synchronized (outputLock) {
writer.write(value);
writer.newLine();
if (autoFlush) {
flush();
}
}
} catch (IOException e) {
throw ErrorMessages.MESSAGES.operationFailed(UncheckedIOException::new, e, "write"); (4)
}
}
@Override
public void close() {
try {
synchronized (outputLock) {
writer.close();
}
AppLogger.LOGGER.tracef("ContentWriter %s was successfully closed.", this);
} catch (Exception e) {
throw ErrorMessages.MESSAGES.closeFailure(e, this);
}
}
/**
* Safely close this writer logging any errors that occur during closing.
*/
public void safeClose() {
try {
synchronized (outputLock) {
writer.close();
}
AppLogger.LOGGER.tracef("ContentWriter %s was successfully closed.", this);
} catch (Exception e) {
AppLogger.LOGGER.closeFailure(e, this); (5)
}
}
1 | Logs the application version. Note this uses the @Once annotation to indicate this should only be logged once regardless of which write method is used. |
2 | The ErrorMessages.nullParam() returns a java.lang.function.Supplier . This allows the message to be lazily formatted only if the value is null . |
3 | Throws a message if the value is an empty string. |
4 | Uses a java.lang.function.BiFunction to create a new UncheckedIOException with the caught exception set as the cause. |
5 | Logs the caught exception instead of throwing a new exception. |