A collection of potentially useful classes for streamlining the process flow of Java applications.
...
import net.calledtoconstruct.Either;
import net.calledtoconstruct.Left;
import net.calledtoconstruct.Right;
public Either<..., String> getData() {
try {
...
final var data = repository.findAll();
...
return new Left<>(data);
} catch (final DataAccessException exception) {
return new Right<>(exception.getMessage());
}
}
A collection of one or more values of discrete data types. In contrast to Array or List which require elements of the collection to share the same data type, the Tuple interface and implementations, allow for elements of different data types. However, the trade-off is that Tuple can only support a small number of elements. This library currently supports up-to four (4) elements.
Implementations:
-
Tuple1 - Example: new Tuple1<String>
-
Tuple2 - Example: new Tuple2<String, Integer>
-
Tuple3 - Example: new Tuple3<Long, String, String>
-
Tuple4 - Example: new Tuple4<MyClass, Long, Long, String>
-
Tuple5 - Example: new Tuple5<String, Integer, Long, Short, Char>
-
Tuple6 - Example: new Tuple6<Integer, Long, Short, Char, Byte, Float>
-
Tuple7 - Example: new Tuple7<MyClass, String, Long, Double, String, Integer, Integer>
-
Tuple8 - Example: new Tuple8<Double, Double, String, Long, Short, String, String, Integer>
...
This builds on the Either example:
import org.springframework.util.StopWatch;
import net.calledtoconstruct.Either;
import net.calledtoconstruct.Left;
import net.calledtoconstruct.Right;
import net.calledtoconstruct.Tuple3;
public Either<Tuple3<List<Entity>, Long, Long>, String> getDataAndCountTimed() {
try {
final var stopWatch = new StopWatch();
stopWatch.start();
final var rows = repository.findAll();
final var count = repository.count();
stopWatch.stop();
final var duration = stopWatch.getLastTaskTimeMillis();
return new Left<>(new Tuple3<>(rows, count, duration));
} catch (final DataAccessException exception) {
return new Right<>(exception.getMessage());
}
}
@GetMapping("/data/{id}")
public String get(final @PathVariable int id, final Model model) {
final var instantNow = Instant.now();
final var currentDateAndTime = Date.from(instantNow);
final var titleAndDate = TITLE.push(currentDateAndTime);
final var result = new Right<String, Integer>(id)
.flip()
// Load the entity, when not found, return a placeholder object.
.<FlowData>onLeftFlatMap(dataService::getById, dataService::createPlaceholder)
.onLeftApply(titleAndDate::push)
.onLeftAccept(titleDateAndFlowData -> populateModel(model, titleDateAndFlowData))
.onLeftSupply(() -> "ThymeLeaf_Template_Name");
return Either.coalesce(result);
}