How to split an input text into arguments

Hi dear Apache commons-cli lover,

You know certainly how to parse a list of arguments into options.

But possibly you may want to provide the same as a pure JVM method ; what about the : callWith(String theArgs) ?

Might sound impossible with a commons-cli library.
You probably have thought about splitting around whitespace tokens, but you forgot that arguments can contain whitespaces characters themselves.

Then how to achieve the parsing from a simple text ?
My solution is to build a powerful regex, using an online IDE called regex101.

An argument can be this, « that », ‘that’, ‘or  »even » that’. Use the regex here from the hyperlink into your code to build a list of arguments from a plain text command line.

How to colorize an xml by code

The following class will help you to do that.

You can easily transform this :

<?xml version="1.0" encoding="UTF-8"?>
<kcfg xmlns=""
    <kcfgfile name=""/>
    <group name="com.librehat.yahooweather">
        <entry name="woeid" type="String">
        <entry name="interval" type="Int">
        <entry name="celsius" type="Bool">
        <entry name="fahrenheit" type="Bool">
        <entry name="ms" type="Bool">
        <entry name="kmh" type="Bool">

Into this :


import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class XmlInColorsConverter {

    public static void main (String [] args) throws IOException {
        Scanner scanner = new Scanner(new File(args[0]));
        System.out.println(new XmlInColorsConverter().convert(;

    private static final Pattern NAME = Pattern.compile("(?:([a-zA-Z][a-zA-Z0-9]+):)?([a-zA-Z][a-zA-Z0-9._]+)");
    private static final Pattern VAL = Pattern.compile("\"((?:[^\"]|(?< =\\\\)\")*)\"");
    private static final Pattern ATTR = Pattern.compile("(" + NAME + ")\\s*(=)\\s*(" + VAL + ")\\s*");
    private static final Pattern MARKUP = Pattern.compile("(\\s*)(< )(/|\\?)?" + NAME + "\\s*(?:" + ATTR + ")*(/|\\?)?>");

    public String convert(String text) {
        return colorize(text, MARKUP.matcher(text));

    private static String colorize(String input, Matcher matcher) {
        int lastEnd = 0;
        int level = 0;
        StringBuilder result = new StringBuilder();
        while (matcher.find()) {
            String oneMarkup =;
            Matcher attrMatcher = ATTR.matcher(oneMarkup);
            String afterLastMatch = input.substring(lastEnd, matcher.start(2) == -1 ? 0 : matcher.start(2));
            level -= "/".equals( ? 1 : 0;
            if (afterLastMatch.matches("\\s*")) {
                result.append("\n").append(IntStream.range(0, level).boxed().map(i -> "    ").collect(Collectors.joining()));
            }else {
            level += == null ? 1 : 0;
            result.append("\033[1;33m< ").append(( != null ? : "")).append(( != null ?  "\033[34m" + + "\033[1;33m:" : "\033[1;33m")).append("\033[0m");
            while (attrMatcher.find()) {
                result.append(" ").append(( != null ? "\033[34m" + + "\033[35m:" : "\033[35m")).append("\033[32m=\033[36m").append(;
            level -= "/".equals( ? 1 : 0;
            result.append("\033[1;33m").append(( != null ? : "")).append(">\033[0m");
            lastEnd = input.charAt(matcher.end()) == '\n' ? matcher.end() + 1 : matcher.end();
        return result.toString();

Java : How to speak about events in a material world

The title of this article is assumed to not be IT related, but it speaks about java. I just wanted it to be of common sense.

Most people writing software today only speak about what we have (the objects), and not about what we know (the events). And sometimes they refuse to understand the meaning of the knowledge (with its history) in favor of its only content.

But sometimes it can be useful.

« History is not important » means « Giving the money to the wrong person is not important ». Why do I say that ?
If we address a bank check of $100 to a Mr John and then a malicious person adds an ‘s’ to the recipient, it will become Mr Johns. We give the money anyway, and we don’t know that we gave it to the wrong person… In fact, our bank account does not notice the problem, we are debited of $100. We are attacked and we just lost data about the attack.

What is the problem behind ? We lose track of known data just because the state has changed.
How to deal with ? Well it is quite simple : past history won’t change.

Therefore, storing the past data can ensure everything gets tracked. The bank check will be photocopied before and after each event (like someone appending a ‘s’ char to a family name). Therefore we can validate that nothing wrong has happened during the process by scanning the bank check history.

Howto ? You can implement it on your own, but that is really a boilerplate to code.
I have tried the JaVers library and wrote a very small webapp to maintain an in-memory user api (

Things stay simple : just keep on persisting your data as you would in a non-event-sourced program, but at the last moment, let JaVers work directly with the repository as following :
interface PersonRepository extends MongoRepository {}

You are now able to query data as usual, but also examine the changes in data and read some old snapshots : (

Then, reading the current state of the bank check would need to get
Reading the old values of the bank check is as easy as reading

…And you can figure out that someone replaced « Mr John » by « Mr Johns » by reading !
The response will look like this :
1. ValueChange{
property:'to', oldVal:'Mr John', newVal:'Mr Johns'}

Then, you will go beyond things, you will be less materialist and care only about the facts… what matters really to your users.

Jackson : Make the most of POJO versus Immutable Objects

There is a simple dilemma that comes into my thoughts :
-> I have an object, right… class A { String b;int c}
-> It must be filled automatically thanks to unmarshalling from a json string {"b":"val1","c":2}
-> I want it to be immutable because I don’t want to alter my input, or to trust some insecure hashcode/equals methods.

Therefore : I must have a deserializable class, with final fields, a comprehensive constructor, and a builder pattern.

That sounds awkward with jackson. But is it possible ? Yes, it is, and I’ll prove it.

Neat, but let’s complicate this attempt a bit. Suppose we have a polymorphic object to be deserialized. It is a paradigmatic issue between Java and Json : Java is typed, Json does not care.
let’s declare this in pseudo DSL : class TripSegment { TransportMode mode; SegmentDetails detailsOfTheSegment }
and with several details classes like this one : class LocalTransitDetails implements SegmentDetails {String lineCode;DateTime timeOfDeparture;DateTime timeOfArrival;String departureStationName;String arrivalStationName;}

We want neither to create a TripSegmentBean as a POJO, nor to have a non jackson deserializer… So how to ?
Here is how I could successfully answer to that problem :

Now, I can handle my unmarshalled value object as if I built it manually. Now forget about dozer or BeanUtils. Let’s concentrate on the workflow.


Would you enjoy being able to cURL something within one command line in java ?

Seems sometimes annoying to instantiate an HttpPost, or even an HttpClientBuilder, with its fluent interface.

What I suggest you is to use my code sample, to enhance it and to transform it in your customized cURL command. You can even add custom arguments to it, so the commands will be shorter to type.

How to use it ? Like a normal curl !
Response curlResponse = curl(" -X'POST' -H'Content-Type:application/x-www-form-urlencoded' -d 'token=mytoken&channel=mychannel' ''")

Here you are, with a curl response that you are able to read easily with the HttpClient API.
Where is this code sample ? There :

EDIT : 2016-07-22 : and

BTW, this blog is now 8 years old, and this is the 200th post… way to go.

Query your app data like you would query a database

The interesting job in creating an app is to send or receive data to another actor :
– whether it is human or not,
– whether it is UI, JSON/Xml/Yaml or console text,
– whether it is a webApp, a program or a script

Now, what happens between the data exchange and the added value of your software ? Boring data manipulation stuff.

Furthermore, let’s imagine that you need to filter every bank account transaction on your account server with a synthetic data (for example, the impact of an economic crisis on the account itself) ?
public float estimatedBalance (int nbDays, float economicHealth)
-> Most of the time you would not compute that with a simple database, because it can depend on some calculation thanks to an algorithm.

Then, build a data cache and try to query your data inside your application instead…
I have 2 solutions to suggest (with a JVM) :
– Switch to Java 8, and to the easy lambda function syntax :
List result = accounts.filter(account -> account.estimatedBalance(90, -1) < max);
– Use my lib : You are now able to query some java objects by using a simplified query syntax. You can even pass a String object and therefore construct a query on your own java objects. On the homepage of this project, you will get a preview of what can be done using this syntax.

It can be used as a backend if you don’t need to persist the data really. I am actually thinking if it could be useful to actually save the data in a file…

How to read an ogg file in Java without JNI

  1. Import jorbis as a dependenyc of your project
  2. Read the howto :
  3. Copy the source code. It will work, but will only be able to play a sound (not to convert it)
  4. Look at my JorbisCleanConverter. ( and copy everything (you will need to change the catch clauses).
  5. You are now able to transform an ogginputstream into a wav outputstream using a ByteArrayInputStream class. To get the stream entirely, just do .toByteArray(), you can write that in a file and use it as a real wav file.

Java : How do I prevent my non public classes from being used outside my lib

There is a simple problem that a lot of developers may ask to their teammate or themself :
– I wrote a MyComponent class in a lib project, under the bar package

package bar;
public class MyComponent {
public void doIt () {}

– This class is not going to be used outside this project
– Then, how can I hide this to the users ? How can I prevent the users to play with the class MyComponent ? How can they consider my lib as a trustable and reliable black box instead of a collection of mysterious functions ?

Maybe there is another way… I will explain mine, and I think there are other ways to do that, better or worse.

1. Let’s try to declare a contract between you and the client code
A smarter approach can be to implement an interface with all the public methods which can be called from outside.

package bar;
public class MyComponent implements Component {
public void doIt () {}

public interface Component {
void doIt ();

This is a nice try, because now the client code will be advised to use Component as the preferred type to execute your methods.
You will still need to call the MyComponent constructor this way :

Component fooComponent = new MyComponent ();

The client code does not need to know what kind of Component we have.

2. Isolate the construction of your MyComponent class
You can think of a static method to reach the MyComponent class constructor.
Remove the public modifier in the MyComponent class.
Make the MyComponent constructor package scope so it is not usable by some reflection libs unless cracked in a dirty way.
Make the MyComponent class final so nobody can cheat with it.

package bar;
final class MyComponent implements Component {
MyComponent () {}
public void doIt () {}

Create an accessor in the same package as MyComponent, and leave it abstract :

package bar;
public abstract class ComponentAccessor {
public Component provideComponent (){
return new MyComponent ();

3. Separate the interface and the impl
If your project has different levels of abstractions, it can be useful to separate MyComponent and Component in different Java projects.
In my case, for my own lib, I only had to place MyComponent and Component in different package names, let’s say bar.model for Component and bar.infra.service for MyComponent and ComponentAccessor.

4. Build an accessor tree hierarchy
Imagine you have several MyComponent classes and several Component interfaces in different packages.
You can build an Accessor in each package. But how can you summarize them in one class ? Here is the tip : just make them extend each other !

package bar.infra.service;
import bar.model.MyComponent;
public abstract class ComponentAccessor {
public Component provideComponent (){
return new MyComponent ();

package bar.infra.service.operation;
import bar.model.operation.MyOperation;
public abstract class OperationAccessor extends ComponentAccessor {
public Operator provideTheOperator (){
return new MyOperation ();

package bar.infra.service.reader;
import bar.model.operation.MyReader;
public abstract class ReaderAccessor extends OperationAccessor {
public Reader provideTheReader (){
return new MyReader ();

Create a final class for your final accessor. Depending on your needs, you can leave it public. This will not break the principle.

package bar.ioc;
import bar.infra.service.reader;
public final class FinalAccessor extends ReaderAccessor {

Now, you can load your final accessor as if it was an IoC module and load your dependency in a clean and human-readable way.

FinalAccessor accessor = new FinalAccessor ();
Component component = accessor.provideComponent ();
Reader reader = accessor.provideReader ();

5. Forbid any use of a subclass of ComponentAccessor
Even if the FinalAccessor is final, someone can still extend ReaderAccessor and declare again some provide methods.
You can use a tip to detect if someone is trying to code an accessor on his own by detecting if the package name is right.
Make the ComponentAccessor extend a RootAccessor like this :

package bar;
public abstract class ComponentAccessor extends RootAccessor {
public Component provideComponent (){
return new MyComponent ();

In the RootAccessor, test the package name and throw an exception if it does not match with what you expect

package bar;
public abstract class RootAccessor (){
public RootAccessor () {
if (!this.getClass ().getPackage ().getName ().startsWith (RootAccessor.class.getPackage ().getName ())) {
throw new MyException ("Not allowed to create an accessor outside the package");

Well done : you have protected your lib against a too smart client code.
Even the IDE will help you : in the auto-completion tab, you will only see the interface classes (Component, Reader,…) and the Accessors (RootAccessor, ComponentAccessor). The MyOperation, MyComponent or MyReader classes will not be suggested and therefore will not be available outside your project. Any attempt to use the accessor will result in an exception.

My leasure time library project, soundtransform, uses that pattern, you can have a look at and see the accessors I wrote (start by looking at my AndroidRootModule and my JavaxRootModule in the IoC part of the source code).

Junit : changer la valeur d’un champ ‘private final’ en toute impunité

Si dans une classe A, vous avez un champ private final String foo,
et que dans une classe TestA, vous cherchez à la changer après avoir fait un new, normalement c’est impossible…

Normalement, parce qu’il existe toujours une astuce pour contourner cela :

A Ainstance = new A ();
String newValue = "New value here !"
try {
Field fooField = A.class.getDeclaredField("foo");
fooField.setAccessible(true);//ignore private here
Field fieldModifiers = Field.class.getDeclaredField("modifiers");
//Remove private and final here
fieldModifiers.setInt(fooField, fooField.getModifiers() & ~Modifier.FINAL & ~Modifier.PRIVATE);
fooField.set(Ainstance, newValue);
} catch (NoSuchFieldException e1) {
} catch (SecurityException e1) {
} catch (IllegalArgumentException e1) {
} catch (IllegalAccessException e1) {

Une autre possibilité est de toujours passer par les getters pour récupérer la valeur d’un champ et de mocker la méthode getFoo (soit par une sous-classe si A n’est pas final, soit avec un framework genre Mockito)


Sur mon repository github soundtransform, je crois avoir obtenu (par accident) un convertisseur musique vers 8bit.

J’étais en train de chercher comment remodeler un son en le sous échantillonnant pour en supprimer ses pics et ses bruits parasites. En écoutant le résultat de ma transformation, j’ai eu l’étrange impression d’écouter du son de console NES.

Voici le son avant : Tiefschwarz – On Up
Voici le son après : 8bitschwarz – On Up