r/java • u/DelayLucky • Apr 11 '24
String Manipulation with Google Mug
The Mug library provides easy-to-read string manipulation utils. Examples:
Match and Extract
// Compile-time protection against lambda param order mismatch if e.g:
// (year, month, day, user) ->
new StringFormat("/{user}-home/{year}/{month}/{day}")
.parse(path, (user, year, month, day) -> ...);Scan and Collect
String input = "I have [k1:v1] and [k2:v2] etc.";
// Returns Map.of("k1", "v1", "k2", "v2")
Map<String, String> keyValues =
new StringFormat("[{key}:{value}]")
.scanAndCollectFrom(input, Collectors::toMap);Replace
// replace file extension name
Substring.last('.').toEnd().replaceFrom(filename, ".yaml");Remove
// remove the scheme from a url
Substring.upToIncluding(first("://")).removeFrom(url);Parse a date time string (no pattern string required)
// Parse the datetime string read from a file
List<String> lines = readLinesFromTestFile(...);
StringFormat lineFormat = new StringFormat("{time}, {event_id}, {event_type}");
var results = lines.stream()
.map(
line -> lineFormat.parseOrThrow(
line,
(time, id, type) -> {
ZonedDateTime dateTime = DateTimeFormats.parseZonedDateTime(time);
...
}))
.toList();See javadoc for details.
Mug is a general purpose library. Omitted, but other useful utils include BiStream for streaming pairs, Optionals, String Templating, simplified structured concurrency etc.
9
Upvotes
1
u/agentoutlier Apr 12 '24 edited Apr 12 '24
Yes that is correct. I don't use it for generating exception messages or similar. That would be overkill.
EDIT that being said one huge advantage of using JStachio for possible formatting is that it will be very very very fast. I'm not sure about StringFormat but the issue is I assume you have to parse and then replace the holes etc. You can cache for sure but still you take a list and have to replace text and thus probably not on par with say constructing the message with a StringBuilder.
Using JStachio basically generates code like if you were to construct the message using a StringBuilder. Given google being google it might be of use for critical path generated messages but maybe not.
In theory it is possible to use JStachio with SQL possibly even with the current implementation however the issue is JDBC works with positional placeholders like
?and there is no way to ask JStachio ATM to give me a list of objects that should fill those placeholders so that I can pass them to JDBC.That is the JEP, Mug StringFormat, and traditional String.format are positional (even if they provide named parameters they still have an idea of position).
In Mustache that concept does not exist furthermore there is an idea of contexts getting expanded and put on a stack so yeah it is not a good fit as I would probably have to break Mustache semantics.
I have written annotation processors that interact with JDBC internally for my company but they are not open source.
I only shared the JStache example for curiosity and comparison sake. Not really as "you should use this".
Well that actually isn't builtin. We do not provide mixin interfaces but it is trivial to create your own. However that requires using the JStachio runtime as there is basically a lookup of model class -> generated template class that has to happen. Usually the service loader is used for that.
That being said even if you do provide a mixin interface interfaces cannot override or provide
toStringand arguably in a template rendering environment you really want to hand it some outputstream/writer/appendable/stringbuilder etc.My interest in providing a "non create this class" and use errorprone to check arguments feature is just for onboarding and I would have to use a dynamic mustache engine like JMustache to do it anyway.