Friday, May 20, 2016

Mutable boolean

Sometimes you have already a return value in your java function, but you need to update a boolean field from another function. If you try to give the reference of Java Boolean, it is not working.

public void refresh(Object data){
   Boolean isChanged = Boolean.FALSE;
   updateFirstPart(data, isChanged);
   updateSecondPart(data, isChanged);
   if (isChanged) {
      saveData(data);
   }
}

protected void updateFirstPart(Object data, Boolean isChanged){
   if(conditions...){
       data.setName("vmi");
       isChanged = Boolean.TRUE;
   }
}

The data will be never saved, the isChanged filed keeps the false value.



So for this we a Mutable Boolean type in Apache commons lang.

import org.apache.commons.lang3.mutable.MutableBoolean;
public void refresh(Object data){
   MutableBoolean isChanged = new MutableBoolean(false);
   updateFirstPart(data, isChanged);
   updateSecondPart(data, isChanged);
   if (isChanged.isTrue()) {
      saveData(data);
   }
}

protected void updateFirstPart(Object data, MutableBoolean isChanged){
   if(conditions...){
       data.setName("vmi");
       isChanged.setTrue();
   }
}

Tuesday, May 10, 2016

String.startWith() challange, remove your BOM


The system receives SOAP messages, they contain Base64 encoded XML content, we use as a String in the application layer and store as clob in the database.


http://unsolublesugar.com/20120919/223812/

We introduced a validation process to check this content, sometimes we have to use an ERROR status for example because the XML format is not good.

This validation process first step to check the XML first row and should find: <!DOCTYPE .... But when we deploy to production we create always the ERROR status, the validation result is negative. Fortunately we store the XML content in the database and I found there the first character is very strange: \FFFE.

OK, it is a BOM, I have to find a way to skip the BOM to able to test the doctype.

We already use apache commons-io in the project and I found the BOMInputStream solution.

Here you are my utility static method to convert the Base64 content to String and remove the possible BOM.

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BOMInputStream;


    public static String removeBOM(byte[] input) throws IOException {
        if (input == null) {
            return "";
        }
        StringWriter writer = new StringWriter();
        IOUtils.copy(new BOMInputStream(new ByteArrayInputStream(input)), writer, UTF_8);
        return writer.toString();
    }